Let’s say, for the sake of argument, that you’re working in C++ and you happen to be in an environment where exceptions don’t work. In my case, it was an embedded environment where the miniaturized C++ standard library didn’t support them, but in your case it may be that you can’t use them for performance reasons, or they’re against policy or something else.
As opposed to the old C-style return codes, C++ exceptions offer five major advantages:
- They are out of band (that is, a function returning an integer need not assign a special value, e.g. -1, to mean “error”).
- They can carry information about the specific error that occurred, as opposed to simply a code with a general meaning.
- They exist in a type hierarchy. A
FileNotFoundExceptionmay be derived from a
FileIOException, and a handler for the latter can handle the former.
- If you ignore them, your program blows up. This is a good thing – an undetected error is far worse than a fatal error.
- They automatically unwind the stack to find a handler.
And these are all reasons why, unless you have a good reason not to, you should prefer using exceptions. But in the case when you can’t, it turns out that point 5 is really the only advantage that you have to do without. There’s a relatively elegant method that you can use to achive the first four advantages without using exceptions at all.