6. Hints on using exceptions
We make a few remarks on using exceptions.
1. Don't overuse exceptions.
Don't use exception handling to replace simple tests. Handling an exception takes far more time than an equivalent simple test, but that is not the real reason for not using exception handling. The ability to throw an exception in a method is there to take care of really abnormal errors that the method itself can't be expected to handle and that should therefore be handled by the calling method (or its caller ...). Don't use exception handling for other things.
2. Use exceptions when the method in which an abnormal event occurs is not the best place to handle it.
For example, if you are writing a method that processes a sequence of characters of a particular form and a sequence is given that does not have the form, the error is the caller's, and the calling place is the best place to handle it.
3. Don't make try-blocks too small.
All other things being equal, it is better to have the whole body of a method enclosed in a single try-statement with several catch clauses than to have many smaller try-statements each with one catch clause. If an abnormal event happens, quite likely you'll want the method to terminate anyway.
4. Don't hide exceptions.
When an error message tells you that a try-block is needed, the tendency is to write one hurriedly,like this one:
try {
some code
}
catch (...Exception ex) {}
Here, the catch-block does nothing, and the program just goes on as if nothing happened. You do this because you don't expect the exception to happen. But when it does, and it takes you several days to find the problem, you'll be sorry.
©This material is from the CD ProgramLive by David Gries and Paul Gries