C++ says “We have try. . . finally at home”
Source: Hacker News
Languages with finally
Many languages¹ that have exceptions also have a finally clause, so you can write
try {
// stuff
} finally {
always();
}
A quick check shows that this control structure exists in Java, C#, Python, JavaScript, but not C++.
C++ says, “We have try…finally at home.”
C++ approach
In C++, the way to get a block of code to execute when control leaves a block is to put it in a destructor, because destructors run when control leaves a block. This is the trick used by the Windows Implementation Library’s wil::scope_exit function: the lambda you provide is placed inside a custom object whose destructor runs the lambda.
auto ensure_cleanup = wil::scope_exit([&] { always(); });
/* stuff */
Although the principle is the same, there are some quirks in how each language treats the case where the finally or destructor itself throws an exception.
Exception‑handling semantics
If control leaves the guarded block without an exception, then any uncaught exception that occurs in the finally block or the destructor is thrown from the try block. All the languages seem to agree on this.
If control leaves the guarded block with an exception, and the finally block or destructor also throws an exception, the behavior varies by language.
| Language | Behaviour when both throw |
|---|---|
| Java, C#, JavaScript | The exception thrown from the finally block overwrites the original exception; the original exception is lost. |
| Python (≥ 3.2) | The original exception is saved as the context of the new exception, but the new exception is the one that propagates. |
| C++ | An exception thrown from a destructor triggers automatic program termination if the destructor is running due to another exception.¹ |
So C++ gives you the ability to run code when control leaves a scope, but your code had better not allow an exception to escape if you know what’s good for you.
Notes
¹ The Microsoft compiler also supports the __try and __finally keywords for Structured Exception Handling. These are intended for C code; using them in C++ can interact with C++ exceptions in confusing ways. See the discussion on Old New Thing.
² This is why wil::scope_exit documents that it will terminate the process if the lambda throws an exception. An alternate function, wil::scope_exit_log, logs and then ignores exceptions thrown from the lambda. There is no variation that gives you Java‑like behaviour.