Sagar
Sagar

Reputation: 191

c++ destructor throw exception by single object

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

Answers (2)

Slava
Slava

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

Cheers and hth. - Alf
Cheers and hth. - Alf

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

Related Questions