I just spent a few hours reading through SO questions on the topic of when to use exceptions, and it seems like there are two camps with different point of views:
Is this just a controversial topic with no widely accepted best practice?
Although structured exception handling is the recommended way of handling error conditions, make sure you use exceptions only in exceptional circumstances when error conditions occur.
Exceptions should be used for situation where a certain method or function could not execute normally. For example, when it encounters broken input or when a resource (e.g. a file) is unavailable. Use exceptions to signal the caller that you faced an error which you are unwilling or unable to handle.
C does not provide direct support for error handling (also known as exception handling). By convention, the programmer is expected to prevent errors from occurring in the first place, and test return values from functions.
As such, C programming does not provide direct support for error handling but being a system programming language, it provides you access at lower level in the form of return values. Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno.
As you can probably gather from the wealth of answers, there is certainly no consensus.
Semantically, exceptions and error provide the exact same functionality. Indeed they are identical in about all semantic aspects, and errors can be arbitrarily enriched much like exceptions (you don't have to use a simple code, you can use a real bundle of data!).
The only difference there is is their propagation methods:
On the other hand:
The very reason both solutions can appear clunky is simply that error checking is difficult. Indeed most of the code I am writing daily concerns error checking, whether technical or functional.
So what to do ?
Warning: demonstration ahead, jump over to the next section if you care only for an answer
I personally like to leverage the type system here. The typical example is the pointer-reference dichotomy: a pointer is like a reference that can be null (and reseated, but it does not matter here)
Therefore, instead of:
// Exceptions specifications are better not used in C++ // Those here are just to indicate the presence of exceptions Object const& Container::search(Key const& key) const throw(NotFound);
I will tend to write:
Object const* Container::search(Key const& key) const;
Or better yet, using clever pointers:
Pointer<Object const> Container::search(Key const& key) const; template <typename O> O* Pointer<O>::operator->() const throw(Null); template <typename O> O& Pointer<O>::operator*() const throw(Null);
Here I find the use of exception superfluous for 2 reasons:
I don't have a problem with exceptions per se, but they can make the code awkward, consider:
void noExceptions(Container const& c) { Pointer<Object const> o = c.search("my-item"); if (!o) { o = c.search("my-other-item"); } if (!o) { return; } // nothing to be done // do something with o }
And compare it with the "exception" case:
void exceptions(Container const& c) { Object const* p = 0; try { p = &c.search("my-item"); } catch(NotFound const&) { try { p = &c.search("my-other-item"); } catch(NotFound const&) { return; // nothing to be done } } // do something with p }
In this case, the use of exceptions does not seem appropriate :/
On the other hand:
try { print() << "My cute little baby " << baby.name() << " weighs " << baby.weight(); } catch(Oupsie const&) { // deal }
is certainly more appealing than:
if (!print("My cute little baby ")) { /*deal*/ } if (!print(baby.name())) { /*deal*/ } if (!print(" weighs ")) { /*deal*/ } if (!print(baby.weight())) { /*deal*/ }
What is the best then ?
It depends. Like all engineering problem there is no silver bullet, it's all about concessions.
So keep 2 things in mind:
If you find yourself wondering whether to use an exception or not, just try to use your API. If there is no clear cut winner, it is just that: there is no ideal solution.
Oh, and do not hesitate to refactor your API when it becomes clear that the error reporting mechanism elected at the time of crafting it is no longer appropriate. Don't be ashamed: requirements change with time, so it is normal that the API change with them.
Personally I tend to use exceptions for unrecoverable errors only: I therefore have few try/catch in my code, only in the outermost levels, to accurately log the error (love stack frames) and log a dump of the BOM as well.
This is very similar (and indeed strongly influenced) by Haskell, the code there is seggregated in two clear cut parts: while any can throw exceptions, only the IO part (the extern one) may actually catch them. Therefore, the pure part must deal with error conditions with other ways in case they are "normal".
If, however, I am faced with a problem where using an exception makes the code easier to read and more natural (which is subjective) then I use an exception :)
I don't think this is a discussion which is exclusive to the C++ community, but here are two high-level guidelines which have helped me:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With