Today I read this question on ars technica which mirrors a question I was asked a few weeks back by one of the junior programmers: why don’t we return booleans or error objects or whatever when something goes wrong in the server? After all, collective wisdom has it that exception handling is slow – unwinding the stack can be a lengthy process, relative to almost anything else in CS, except perhaps I/O.
Indeed, exceptions are slower than just returning a boolean or a string or, as the article suggest, an exception. But that is not an argument. There are extremely good reasons for electing to use exception handling, besides “this is how everyone else does it”.
For this project I have chosen to use exceptions as the primary mechanism for communicating errors; exceptions are for exceptional conditions, and by nature they should be the… well, exceptions.
The reasons for using exceptions are
- They are a built-in mechanism for handling exceptional conditions, at least in imperative, object oriented languages (functional languages have another standard mechanism).
- They provide a natural way to halt execution; when using return values instead you force the programmers to actually handle the error in an if-statement. This means that the programmers must constantly be aware of this fact, and manually halt/branch execution due to an error condition, which is a source for errors in the code.
- Uncaught exceptions are shown immediately when they occur, given that the software will eventually be in the state that produces this error. On the other hand a return value, which the programmer forgot to check for, goes unnoticed.
This doesn’t mean that exceptions should be used any where, any time. In some pieces of the code it might be better practise to use return values instead. For example in often-run methods, or methods that often fail due to error conditions.
Good unit tests must prove the validity and correctness of the code for any error condition, regardless of mechanism.