r/cpp • u/User_Deprecated • Jul 11 '26
Propagating exceptions from destructors with std::exception_ptr
https://www.sandordargo.com/blog/2026/07/08/exception_ptr
80
Upvotes
r/cpp • u/User_Deprecated • Jul 11 '26
View all comments
Show parent comment
3
u/SirClueless Jul 11 '26
In the example in the article, we are calling the destructor while unwinding the stack. Unless the caller has written
try/catchthemselves, it's possible (likely, even) that they haven't calledflush(), even if that's an invariant of the happy path. Destructors offer a way to do cleanup on abnormal exit, and sometimes that cleanup is unavoidably expensive. Logging, writing to disk or the network, committing to a database, etc. are all reasonable things to want to do in cleanup even though they are fallible.This isn't really a property of destructors, or even exceptions: It happens also in languages with
finallyblocks, or scope guards, ordefer/errdefer. Heck, it can happen in plain C, in agoto fail;type block. "An error happened, and then while handling that error another error happened" is a pretty common state to need to represent. Stashing the second error in astd::exception_ptrthe caller can check after handling the primary error sounds pretty reasonable to me: Adds complexity but not as much as turning every error into a chain or set of every possible errors that can happen during cleanup, and more robust than just terminating the program or logging and forgetting the error.