Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why destructor is not called on exception?

I expected A::~A() to be called in this program, but it isn't:

#include <iostream>  struct A {   ~A() { std::cout << "~A()" << std::endl; } };  void f() {   A a;   throw "spam"; }  int main() { f(); } 

However, if I change last line to

int main() try { f(); } catch (...) { throw; } 

then A::~A() is called.

I am compiling with "Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86" from Visual Studio 2005. Command line is cl /EHa my.cpp.

Is compiler right as usual? What does standard say on this matter?

like image 600
Constantin Avatar asked Oct 21 '08 14:10

Constantin


People also ask

Is destructor called on exception?

Yes, destructors are guaranteed to be called on stack unwinding, including unwinding due to exception being thrown. There are only few tricks with exceptions that you have to remember: Destructor of the class is not called if exception is thrown in its constructor.

Why can't you throw exceptions from a destructor?

You can throw an exception in a destructor, but that exception must not leave the destructor; if a destructor exits by emitting an exception, all kinds of bad things are likely to happen because the basic rules of the standard library and the language itself will be violated.

Why is my destructor not called?

There are two reasons that your destructors aren't being called, one is as kishor8dm pointed out that you are using the operator "new" and because of that the "delete" command must be called explicitly.

Is destructor called when exception is thrown in constructor?

When an exception is thrown from a constructor, the object is not considered instantiated, and therefore its destructor will not be called. But all destructors of already successfully constructed base and member objects of the same master object will be called.


1 Answers

The destructor is not being called because terminate() for the unhandled exception is called before the stack gets unwound.

The specific details of what the C++ spec says is outside of my knowledge, but a debug trace with gdb and g++ seems to bear this out.

According to the draft standard section 15.3 bullet 9:

 9 If no matching handler is found in a program, the function terminate()   (_except.terminate_)  is  called.  Whether or not the stack is unwound   before calling terminate() is implementation-defined. 
like image 159
lefticus Avatar answered Oct 05 '22 03:10

lefticus