Reputation: 191
I'm trying to understand why throwing an exception from a destructor results in a program crash. As I found many examples of two object which throw multiple exception and compiler can't handle multiple exception but in my case I only have a single exception thrown from the destructor. Why is my program still crashing?
class MyClass {
private:
string name;
public:
MyClass (string s) :name(s) {
cout << "constructor " << name << endl;
}
~MyClass() {
cout << "Destroying " << name << endl;
throw "invalid";
}
};
int main( )
{
try {
MyClass mainObj("M");
}
catch (const char *e) {
cout << "exception: " << e << endl;
cout << "Mission impossible!\n";
}
catch (...) {
cout << "exception: " << endl;
}
return 0;
}
Upvotes: 3
Views: 1301
Reputation: 44248
Since C++11 destructors are implicitly declared as noexcept
documentation
non-throwing functions are all others (those with noexcept specifier whose expression evaluates to true as well as destructors, defaulted special member functions, and deallocation functions)
emphasis is mine.
Upvotes: 2
Reputation: 145269
Explanation from the MingW g++ compiler:
[P:\temp] > g++ foo.cpp foo.cpp: In destructor 'MyClass::~MyClass()': foo.cpp:14:15: warning: throw will always call terminate() [-Wterminate] throw "invalid"; ^~~~~~~~~ foo.cpp:14:15: note: in C++11 destructors default to noexcept
To really let it throw you can do this:
~MyClass() noexcept(false){
Upvotes: 6