Tech News
← Back to articles

C++ says “We have try at home”

read original related products more articles

Many languages¹ that have exceptions also have a finally clause, so you can write

try { ⟦ stuff ⟧ } finally { always(); }

A quick checks shows that this control structure exists in Java, C#, Python, JavaScript, but not C++.

C++ says, “We have try …finally at home.”

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.

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, then the behavior varies by language.

In Java, Python, JavaScript, and C# an exception thrown from a finally block overwrites the original exception, and the original exception is lost. Update : Adam Rosenfield points out that Python 3.2 now saves the original exception as the context of the new exception, but it is still the new exception that is thrown.

... continue reading