It's not a good idea to let exceptions "escape" from a destructor. If the destructor is being called in response to stack unwinding caused by an exception, allowing an exception to escape results in a call to std::terminate(). Nothing can be done to resume the program. It's fatal. Because of this behavior, we would like to be very sure we don't allow exceptions to escape from destructors.
One approach to this problem is to simply ignore all exceptions that occur in a destructor by catching them and doing nothing more.
void may_throw_exception();
class X {
public:
X();
~X();
};
X::~X() {
try {
may_throw_exception();
}
catch ( ... ) {
// nothing!
}
}
This is a poor solution, though, as it throws away potentially-valuable information. It could be that a bug is causing an exception here. Ignoring it prevents us from finding this bug. This can be improved on slightly by putting an assert( false )
statement in the catch handler. Still, this assumes that the global policy is to ignore the exception.
A better solution is call some handler function in the catch handler. The handler can be defined elsewhere to match the policy for exceptions in destructors. It may just ignore the exception. It may log it to a file. It may stop in the debugger. It may terminate the program immediately. Whatever the case, those writing the destructor don't have to be concerned with this.
void exception_in_destructor();
void may_throw_exception();
class X {
public:
X();
~X();
};
X::~X() {
try {
may_throw_exception();
}
catch ( ... ) {
exception_in_destructor();
}
}