r/cpp • • Apr 02 '26

What happens when a destructor throws

https://www.sandordargo.com/blog/2026/04/01/when-a-destructor-throws
102 Upvotes

48 comments sorted by

View all comments

Show parent comment

13

u/PJBoy_ Apr 02 '26

You need to explicitly return if you don't want the exception to be rethrown https://godbolt.org/z/8Wze4Mrr5

4

u/The_JSQuareD Apr 02 '26

Wow, nuances upon nuances in this.

It never would have occurred to me that an exception gets implicitly rethrown from a function catch block for a destructor. What's the reason for that behavior?

6

u/PJBoy_ Apr 02 '26

Ctors and dtors are special in that their function-try handlers catch exceptions thrown by construction and destruction of subobjects (member variables and bases) respectively. Because these construction/destruction operations happen outside of the ctor/dtor function bodies, and because function-try handlers in other cases only deal with exceptions thrown in the function body, it was decided that rethrowing those exceptions was a good default behaviour.

1

u/The_JSQuareD Apr 03 '26

Thanks for the explanation. But to be honest I don't really follow how the conclusion (this is sane default behavior) follows from the stated facts.

1

u/sultan_hogbo Apr 03 '26

If it doesn’t throw, what is the state of the object? Can it be considered “fully constructed and valid”?

1

u/The_JSQuareD Apr 03 '26

It's a destructor, so no. And in most cases there wouldn't even be a way to refer to the object anymore since it went out of scope.

I think you could just say the object's state is unspecified, and any code whose behavior depends on the state of the object at that point invokes UB. I believe in most cases relying on an object's state after the destructor has run would be UB anyway (so in the case with no exceptions).

1

u/pjmlp Apr 03 '26

I see, thanks for the tip.