I noticed that you can't throw an exception in a destructor. So my question is what should I do if destructor fails.
Another question is, under what situation a destructor might fail?
Thanks so much
Most people say never throw an exception out of a destructor - doing so results in undefined behavior. Stroustrup makes the point that "the vector destructor explicitly invokes the destructor for every element. This implies that if an element destructor throws, the vector destruction fails...
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.
Explanation: As the func() is throwing a const char* string but we the catch block is not catching any const char* exception i.e. exception thrown is not handled therefore the program results into Aborted(core dumped).
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.
Ignore the error.
A destructor might "fail" if for example the class wraps some kind of output, and the destructor flushes and closes that output. Writing data might fail. Your options then are to terminate the program, or to catch the exception, ignore the error, and return. Usually the right design is to ignore it.
In my example, the class should also have a "close_and_flush" function, which users can call prior to object destruction if they want to know whether it succeeded or not. If the user of your class doesn't care whether the operation failed, then neither do you, and you can safely suppress the exception.
Users can then write code like this:
{
OutputObject OO;
write some stuff to OO, might throw;
do more things, might throw;
try {
OO.flush_and_close();
} catch (OutputException &e) {
log what went wrong;
maybe rethrow;
}
}
Or this:
try {
OutputObject OO;
write some stuff to OO, might throw;
do more things, might throw;
OO.flush_and_close();
} catch (AnyOldException &e) {
log what went wrong;
maybe rethrow;
}
Either way, the only time the object will be destroyed without explicit flushing by the user, is if something else throws an exception and the object is destroyed during stack unwinding. So they already know that their operation has failed, and if necessary they can roll back transactions or whatever else they have to do in response to failure.
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