Exceptions: When Things Go Wrong
10.5 Error Handling and Robust Program Design
Log the Error and Resume
Of course, the advice to stop the program assumes that the program can be
terminated reasonably. Some programs—such as programs that monitor
the space shuttle or programs that control a nuclear magnetic resonance
(NMR) machine—cannot (and should not) be terminated because of such
an error.
Such programs are called failsafe because they are designed to run without termination. For these programs, the exception should be reported in
whatever manner is most appropriate, but the program should continue
running. If the exceptional condition invalidates the program’s computations, then the exception handler should make it clear that the results are
tainted.
Other programs—such as programs that analyze a large transaction
database—should be designed to continue processing after catching such errors. For example, suppose a large airline runs a program
once a day to analyze the ticketing transactions that took place. This
kind of program might use exceptions to identify erroneous transactions
or transactions that involve invalid data of some sort. Because there are
bound to be many errors of this kind in the database, it is not reasonable to stop the program. This kind of program shouldn’t stop until it
has finished processing all of the transactions. An appropriate action for
this kind of program is to log the exceptions into some kind of file and
continue processing the transactions.
Suppose a divide-by-zero error happened in one of these programs. In
that case, you would override Java’s default exception handling to ensure
that the program is not terminated. More generally, it’s important that these types of programs be designed to catch and report such exceptions.
This type of exception handling should be built right into the program’s
design.