I wonder whether (and how) it's possible to catch an exception thrown in a member destructor. Example:
#include <exception>
class A
{
public:
~A() {
throw std::exception("I give up!");
}
};
class B
{
A _a;
public:
~B() {
// How to catch exceptions from member destructors?
}
};
Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate.
Destructors are only called for the completely constructed objects. When the constructor of an object throws an exception, the destructor for that object is not called.
How can I handle a failure in the destructor.? A failure in the constructor can be handled by throwing an exception, where as throwing an exception in the destructor will lead to stack unwinding.
You would catch the exception in the calling code, not in the constructor. Exceptions aren't returned in the same way as return values, they skip up the stack to the first appropriate catch block, so whilst you can't return a value from the constructor you can throw an exception from it.
Yes, you can catch such an exception, using the function-try-block:
class B
{
A _a;
public:
~B() try {
// destructor body
}
catch (const std::exception& e)
{
// do (limited) stuff
}
};
However, you cannot really do much with such an exception. The standard specifies that you cannot access non-static data members or base classes of the B
object.
Also, you cannot silence the exception. Unlike with other functions, the exception will be re-thrown implicitly once the function-try-block handler of a destructor (or constructor) finishes execution.
All in all, destructors should really not throw exceptions.
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