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.
Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate.
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 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.
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.
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 } } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With