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.
Best Solution
Throwing an exception out of a destructor is dangerous.
If another exception is already propagating the application will terminate.
This basically boils down to:
Anything dangerous (i.e. that could throw an exception) should be done via public methods (not necessarily directly). The user of your class can then potentially handle these situations by using the public methods and catching any potential exceptions.
The destructor will then finish off the object by calling these methods (if the user did not do so explicitly), but any exceptions throw are caught and dropped (after attempting to fix the problem).
So in effect you pass the responsibility onto the user. If the user is in a position to correct exceptions they will manually call the appropriate functions and processes any errors. If the user of the object is not worried (as the object will be destroyed) then the destructor is left to take care of business.
An example:
std::fstream
The close() method can potentially throw an exception. The destructor calls close() if the file has been opened but makes sure that any exceptions do not propagate out of the destructor.
So if the user of a file object wants to do special handling for problems associated to closing the file they will manually call close() and handle any exceptions. If on the other hand they do not care then the destructor will be left to handle the situation.
Scott Myers has an excellent article about the subject in his book "Effective C++"
Edit:
Apparently also in "More Effective C++"
Item 11: Prevent exceptions from leaving destructors