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:
- 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!