r/cpp • u/pavel_v • Apr 02 '26
What happens when a destructor throws
https://www.sandordargo.com/blog/2026/04/01/when-a-destructor-throws
102
Upvotes
r/cpp • u/pavel_v • Apr 02 '26
37
u/dustyhome Apr 02 '26
A subtle detail that they don't call out explicitly is that an exception can be thrown inside the destructor, as long as it does not propagate outside of it. That's when noexcept or the already live exception will call terminate. So if you have some logging or cleanup function that may throw, you should wrap them with a catch (...).
42
u/pjmlp Apr 02 '26
The author forgot about other alternative, function try blocks.
However they also seem not to work as expected, when applied to destructors, learnt something new today.
https://godbolt.org/z/4r5o5T1sf
9
u/wannaliveonmars Apr 02 '26
Yeah, it's because desctructors are called during stack unwinding so they are the only functions that can be called after an exception was thrown but before the catch block was reached.
4
u/AdOnly69 Apr 02 '26
Thanks, didn't know that
3
u/bownettea Apr 02 '26
The only case I ever stumbled upon for throwing in a destructor is a scoped guard.
I called a
ScopedStop.Given a device object we stop it to apply some setting, then we must restart at the end.
But start itself might raise, so the exception may bubble out of the destructor.
As a bonus we check for if an exception is already in flight, and if it is we don't restart, since we are already in a failure state and trying to start again may lead to program termination.
It's a nifty little construct. Here is a toy example.
The real deal also only stops and restart if the device is running but I omitted it here for simplicity.
2
u/fluorihammastahna Apr 02 '26
Hm, is it me or the article didn't get the point all the way to the end? I mean, why is it bad in practice?
If I get it correctly, it's because it cannot be caught, and it will also make other exceptions uncatchable. Is this it?
1
u/Olipro Apr 02 '26
I have rarely had a situation where it's "Bad stuff happened in our destructor so we throw to communicate it"
But when I do, I check std::uncaught_exceptions and only throw if there aren't already bad things happening