One of the criticisms levelled at C++ is that its large and complex feature set can be difficult to master, and as someone who’s been programming primarily in C++ for over 15 years and is still discovering new and exciting aspects of the language that’s certainly a viewpoint I can relate to.
One criticism levelled against exceptions is that they negatively impact on performance. In this article I will attempt to address this misconception.
In this post I would like to talk about what I consider to be one of the primary benefits for using exceptions to handle errors. That is, I believe that exceptions improve the flow of the code.
In C++ there is one situation where it is only possible to use exceptions to report an error - when object constructors can fail. In exception-free code bases this leads to the additional requirement that constructors must always succeed. For certain design patterns having constructors that always succeed can simplify code - but in this article I want to look at the knock on effect this decision has on the design of the entire system, and how exceptions actually permit a simplified, more coherent design.
Before I start looking at the drawbacks of exceptions, I want to go over some of the other benefits. To illustrate these benefits I’m going to use a simple function.
Back in 2005 Raymond Chen of Microsoft 1 wrote a piece lamenting exceptions as making a hard problem harder. In this article I want to revisit his thoughts and see how they fit in with what we know 11 years later.
In 2014 Jon Kalb 1 gave a three hour presentation at cppcon on how to write exception safe code 234. In the talk, Kalb sets out a series of guidelines on how to write exception safe code. In this post I’m going to go over those guidelines, with a few small adaptations of my own. If you’re interested in using exceptions in your code I highly recommend the talk, as you will find Kalb’s thoughts mirror many of my own on the subject.
In his cppcon 2014 talk, Jon Kalb 1 gave a quick summary of how to convert legacy code to exception safe code 2. In this post I thought I’d go over his technique, because it is useful to know how to safely and incrementally convert exception-unsafe-code to exception-safe-code.