What to do if a failed destructor can't throw an exception
c++
Solution
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.
Problem
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