Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Arguments for Exceptions over Return Codes

Tags:

c++

exception

I'm having a discussion about which way to go in a new C++ project. I favor exceptions over return codes (for exceptional cases only) for the following reasons -

  1. Constructors can't give a return code
  2. Decouples the failure path (which should be very rare) from the logical code which is cleaner
  3. Faster in the non-exceptional case (no checking if/else hundreds of thousands of times)
  4. If someone screws up the return code settings (forgets to return FAIL) it can take a very long time to track down.
  5. Better information from the message contained in the error. (It was pointed out to me that a return enum could do the same for error codes)
  6. From Jared Par Impossible to ignore without code to specifically designed to handle it

These are the points I've come up with from thinking about it and from google searches. I must admit to being predisposed to exceptions having worked in C# for the past couple of years. Please post further reasons for using exceptions over return codes. For those who prefer return codes, I would also be willing to listen to your reasoning. Thanks

like image 246
Steve Avatar asked Dec 04 '09 20:12

Steve


People also ask

Why are exceptions better than return codes?

An application that uses exceptions is more robust than an application that uses return codes. An application that uses exceptions can also give the cleanest code, since return codes don't have to be checked after every call.

What is one way in which exceptions are superior to error codes?

The biggest benefit exception handling has over error codes is that it changes the flow of execution, which is important for two reasons. When an exception occurs, the application is no longer following it's 'normal' execution path.

Why is it better to use exceptions in C++ programming rather than returning an error code?

Exceptions are preferred in modern C++ for the following reasons: An exception forces calling code to recognize an error condition and handle it. Unhandled exceptions stop program execution. An exception jumps to the point in the call stack that can handle the error.


2 Answers

I think this article sums it up.

Arguments for Using Exceptions

  1. Exceptions separate error-handling code from the normal program flow and thus make the code more readable, robust and extensible.
  2. Throwing an exception is the only clean way to report an error from a constructor.
  3. Exceptions are hard to ignore, unlike error codes.
  4. Exceptions are easily propagated from deeply nested functions.
  5. Exceptions can be, and often are, user defined types that carry much more information than an error code.
  6. Exception objects are matched to the handlers by using the type system.

Arguments against Using Exceptions

  1. Exceptions break code structure by creating multiple invisible exit points that make code hard to read and inspect.
  2. Exceptions easily lead to resource leaks, especially in a language that has no built-in garbage collector and finally blocks.
  3. Learning to write exception safe code is hard.
  4. Exceptions are expensive and break the promise to pay only for what we use.
  5. Exceptions are hard to introduce to legacy code.
  6. Exceptions are easily abused for performing tasks that belong to normal program flow.
like image 172
Nikola Smiljanić Avatar answered Sep 19 '22 06:09

Nikola Smiljanić


The best case I've heard for preferring return codes over exceptions is simply this:

  1. Writing exception-safe code is hard [in C++].

With a great deal of recent experience in C# myself, I can empathize with your desire to use exceptions, but unfortunately C++ isn't C#, and a lot of things that we can get away with in C# can be ultimately deadly in C++.

A good summation of the case for and against can be found in Google's style guidelines. In short:

Pros:

  • Exceptions allow higher levels of an application to decide how to handle "can't happen" failures in deeply nested functions, without the obscuring and error-prone bookkeeping of error codes.
  • Exceptions are used by most other modern languages. Using them in C++ would make it more consistent with Python, Java, and the C++ that others are familiar with.
  • Some third-party C++ libraries use exceptions, and turning them off internally makes it harder to integrate with those libraries.
  • Exceptions are the only way for a constructor to fail. We can simulate this with a factory function or an Init() method, but these require heap allocation or a new "invalid" state, respectively.
  • Exceptions are really handy in testing frameworks.

Cons:

  • When you add a throw statement to an existing function, you must examine all of its transitive callers. Either they must make at least the basic exception safety guarantee, or they must never catch the exception and be happy with the program terminating as a result. For instance, if f() calls g() calls h(), and h throws an exception that f catches, g has to be careful or it may not clean up properly.
  • More generally, exceptions make the control flow of programs difficult to evaluate by looking at code: functions may return in places you don't expect. This results maintainability and debugging difficulties. You can minimize this cost via some rules on how and where exceptions can be used, but at the cost of more that a developer needs to know and understand.
  • Exception safety requires both RAII and different coding practices. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid requiring readers to understand the entire call graph, exception-safe code must isolate logic that writes to persistent state into a "commit" phase. This will have both benefits and costs (perhaps where you're forced to obfuscate code to isolate the commit). Allowing exceptions would force us to always pay those costs even when they're not worth it.
  • Turning on exceptions adds data to each binary produced, increasing compile time (probably slightly) and possibly increasing address space pressure.
  • The availability of exceptions may encourage developers to throw them when they are not appropriate or recover from them when it's not safe to do so. For example, invalid user input should not cause exceptions to be thrown. We would need to make the style guide even longer to document these restrictions!

I suggest reading through and understanding the pros and cons, then making a decision for your own project based on these. You don't have the same software that google has, so what makes sense for them may not make sense for you (which is why I omitted their conclusion).

like image 25
Greg D Avatar answered Sep 20 '22 06:09

Greg D