Java Reference
In-Depth Information
E XCEPTION -P ROCESSING S UGGESTIONS
Exceptions are a very handy way to describe error conditions and ensure that they
are properly managed. As is always true, too much of a good thing is not necessar-
ily a better thing.
One concern is that exception processing is much more expensive than is sim-
ple testing of a value. It is generally better (performance-wise) to test for an error
condition if you can, instead of creating and catching an exception. As a rule, ex-
ceptions should be reserved for unusual error conditions and not as a program-
ming technique to test for anticipated conditions.
For example, the getTranslate() method can throw a NoDatabaseAvailableEx-
ception if no database is available. However, if you simply cannot find the translated
text in the database, you should not treat that condition as an exception. The method
getTranslate() should handle this condition in some fashion, perhaps by logging the
condition to an audit file and returning the original text as the translated text.
Another concern is that a class that throws an exception forces its subclasses
and its consumer classes to handle the exception. A class designer should define and
throw exceptions only when it makes sense for a class consumer to be aware of the
error condition. Of course, if you define a class that uses other classes, and these
other classes throw exceptions, you may have to throw them in the classes you
build if your class cannot handle the exception internally. This situation only high-
lights the potential problems created by the aggressive use of exceptions.
Another related suggestion: Make sure that your base classes that will throw ex-
ceptions are defined that way early in the development process. It is extremely frus-
trating to define a new exception in a low-level class, and then have to edit and
recompile all the classes that use this class. You will need to recompile because
every class that calls a method that can throw an exception must either handle the
exception or throw it.
Make sure that your class is in a proper state if you throw or catch an exception.
Since a throw statement effectively acts as a goto statement and abruptly interrupts
the normal sequence of statements in your class, it is possible that some variable or
object in your object will be in an invalid state the next time your object is accessed.
If necessary, place appropriate code in the finally code block to ensure that your
object is in good shape for the next call.
Finally, group your exception processing into larger try...catch code blocks.
For example, don't insert a try...catch block around every statement that might
create an exception. If a section of code might create several exceptions, it is very
likely that the exception-handling process is the same for each exception. If this is
the case, group the statements into a single, larger try...catch code block.
Search WWH ::




Custom Search