The Error Handling Debate

One of my favorite C++ issues is error handling. C++ exceptions or error codes? It’s a guaranteed fire starter conversation with any group of C++ programmers.
I’m convinced there’s no one right answer when it comes to error handling, because you need to weigh factors such as code consistency, performance, code size, team experience, and readability (among others). It’s also not unreasonable to make different decisions in different parts of a code base (e.g. low levels use EH and high levels use EC or vice versa).
I was recently on an email thread where the discussion was rehashed. Three interesting and useful articles about this topic were highlighted. They’re all worthwhile reading because they cover multiple viewpoints:
Some takeaways:
  • Error handling is important. Have the discussion with your team and make a decision. Consistency is better than haphazard techniques.
  • Avoid raw pointers. No matter what error handling mechanism you choose, your code will be simpler and you will eliminate memory leaks by using shared_ptr<T>.
  • Remember that the C++ Standard Template Library throws exceptions, and new throws exceptions by default, so if you’re using these technologies you need to deal with exceptions at some level.
  • If you go the exception route, make sure everybody on the team has read Herb Sutter’s Exceptional C++ and More Exceptional C++ books.
  • Peer code reviews are essential no matter what method of error handling you choose.

And my opinion in the debate:

  • When I’m writing new C++ code for my own use, I use C++ exceptions. For me, the benefits outweigh the drawbacks.
  • When I’m working in existing code bases, I follow the error conventions already in place. Consistency outweighs all other factors.

Happy error handling!

This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s