Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting when destructor running due to exception being thrown?

Tags:

What is a good way in C++ to detect in a destructor that it is being run during unwind of the stack due to an exception being thrown as opposed to a normal exit of scope triggering the destructor? I'd like to know so that I can create a class that has some cleanup code that is always run on normal exit but skipped when an exception occurs.

like image 726
WilliamKF Avatar asked Aug 22 '11 01:08

WilliamKF


People also ask

What happens when an exception is thrown in a destructor?

Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate.

Is destructor called when exception is thrown?

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.

How do you handle error in destructor?

How to handle error in the destructor? Explanation: It will not throw an exception from the destructor but it will the process by using terminate() function.

What will happen in case of destructor if the exception is raised inside the try block?

CPP. When an exception is thrown, destructors of the objects (whose scope ends with the try block) are automatically called before the catch block gets executed.


1 Answers

std::uncaught_exception() (defined in <exception>) will tell you in your destructor if it was called because of an exception:

class A { public:     ~A()     {         if (std::uncaught_exception()) {             // Called because of an exception         } else {             // No exception         }     } }; 
like image 101
Dave Avatar answered Nov 22 '22 04:11

Dave