If you shouldn’t throw exceptions in a destructor, how do you handle errors in it?

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… There is really no good way to protect against exceptions thrown from destructors, so the library makes no guarantees if an element destructor throws” (from Appendix E3.2).

This article seems to say otherwise – that throwing destructors are more or less okay.

So my question is this – if throwing from a destructor results in undefined behavior, how do you handle errors that occur during a destructor?

If an error occurs during a cleanup operation, do you just ignore it? If it is an error that can potentially be handled up the stack but not right in the destructor, doesn’t it make sense to throw an exception out of the destructor?

Obviously these kinds of errors are rare, but possible.

17 Answers
17

Leave a Comment