Gigi Sayfan discusses various strategies of error handling in C++. He lists exception handling, status/return codes, setjmp/longjmp exception handler, and the global error object. Exception handling is the advocated way of error handling in C++, something that is an improvement over the return codes. Exceptions can be semantically typed as against maintaining a list of error codes and their meanings. It also builds a stack in the process that can be used to dump the entire thread that contains the exception.
However, on the way, a pure exception handling strategy can turn out to be resource expensive. You can optimize exception handling (pdf) and also consider various exception safety levels to support. However, there are scenarios, sometimes out of our control, when pure exception handling cannot be used. Sometimes the code is not any easier when developers have to create their own hierarchies of exceptions, without enough knowledge of designing exceptions. Some of these scenarios lead to decisions of not using exception handling, but to use a balanced approach.
One of the ways is to use exceptions only for certain scenarios, like for the unanticipated ones. The error codes can be used for logical errors. The reasoning behind this is that exception handling provide you a graceful way of handling cleaning up activities like freeing memory. In some cases, when there are no activities to be done, error codes can suffice. Also, Not to say that it is ideal, but has turned out to be practical. One of the popular ways, like Gigi has mentioned, is to encapsulate exception handling behind error codes by handling them at the interface – the boundary of communication with other components.
The problem in such hybrid scenarios however comes up somewhere else – in code management. If use of exception handling or error codes is kept for the choice of programmers, it can end up in a non-compatible error handling scenario. It is of utmost importance to build a error handling policy, or at least guidelines to reduce subjectivity, in such cases, and make it part of coding conventions and code reviews. The policy should mention when to propagate an exception or error and when to handle it internally. Exception handling is an aspect that has the potential to either make the software sturdy or kill the entire project if not designed properly.
