Exception handling in C++ is limited to try/throw/catch. Unlike Object Pascal, Java, C# and Python, even in C++ 11, the finally
construct has not been implemented.
I have seen an awful lot of C++ literature discussing "exception safe code". Lippman writes that exception safe code is an important but advanced, difficult topic, beyond the scope of his Primer - which seems to imply that safe code is not fundamental to C++. Herb Sutter devotes 10 chapters to the topic in his Exceptional C++ !
Yet it seems to me that many of the problems encountered when attempting to write "exception safe code" could be quite well solved if the finally
construct was implemented, allowing the programmer to ensure that even in the event of an exception, the program can be restored to a safe, stable, leak-free state, close to the point of allocation of resources and potentially problematic code. As a very experienced Delphi and C# programmer I use try.. finally blocks quite extensively in my code, as do most programmers in these languages.
Considering all the 'bells and whistles' implemented in C++ 11, I was astonished to find that 'finally' was still not there.
So, why has the finally
construct never been implemented in C++? It's really not a very difficult or advanced concept to grasp and goes a long ways towards helping the programmer to write 'exception safe code'.
finally
in C++, and what techniques for exception handling are used in its place?" is valid and on topic for this site. The existing answers cover this well, I think. Turning it into a discussion on "Are the C++ designers' reasons for not includingfinally
worthwhile?" and "Shouldfinally
be added to C++?" and carrying on the discussion across comments on the question and every answer doesn't fit the model of this Q&A site.