3 ms·
> I've never come across a situation where exceptions during destruction is a problem, but am very interested in any examples. C++ standards define that you _ca
by benlivengood 7y ago
> I've never come across a situation where exceptions during destruction is a problem, but am very interested in any examples. C++ standards define that you _can_ throw exceptions, but you shouldn't for the exact reason raised in the article - the process will be terminated as there's nothing else that can be done. If there aren't any destructors containing the throw keyword, it's not likely to throw an exception - OOM or other system exceptions are still possible, but why are you allocating memory in a destructor? destructors just need to release resources and clear down the object, it shouldn't be requesting more resources. Thinking about saving the object state before exit? wrong place to do it.
std::ofstream is a good example. Flushing and closing the file happens in the destructor if not done explicitly. Not being able to throw IO exceptions from the destructor breaks object encapsulation by requiring explicit error-checking. One could argue that it's simply a bad abstraction; an open file handle is not in a fully consistent state and so a C++ object pretending to be valid while representing a file handle may have been a poor choice as opposed to e.g. record-based or transactional IO where writes could be atomically flushed or fail.
In general any objects representing IO can be victims of error conditions in destructors because external state can change unexpectedly between the last valid state of the C++ object and its destruction, especially if the object abstracts away some non-deterministic behavior.
Destructing objects may also require modification of other data structures: Updating special containers or indexes, unregistering from a queue, waiting for thread completion, etc. This can force destructors to eat exceptions that should otherwise be passed up to callers.