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

16

u/foxsimile Apr 02 '26

It hadn’t ever even occurred to me that

~Thing noexcept(false) try {
  /*…*/
}
catch(…) {
  /*…*/
}

Was even legal syntax.

9

u/n1ghtyunso Apr 02 '26

i believe the main purpose is to wrap constructors in a try-catch in a way that lets you catch exceptions from the constructor initializer list, or from the NSDMI.
Notably, for constructors specifically, it is automatically rethrown from the catch clause.
What it does enable you is to throw a different exception.

I can't think of any use case on regular functions though. Lets you save one pair of braces i guess...

1

u/tangerinelion Apr 03 '26

On a regular function, the advantage of function try is reducing indentation by one level.

When function try blocks are applied to regular functions they also don't have the implicit rethrow behavior.