Exceptions: When Things Go Wrong
10.5 Error Handling and Robust Program Design
Print a Message and Terminate
Our illegal argument example is a clear case in which the exception is best
handled by terminating the program. In this case, this particular error
is best left to Java’s default exception handling, which will terminate the
program when the exception is thrown. There is simply no way to satisfy
the postcondition of the avgFirstN() method when N is less than or equal to 0. This type of error often calls attention to a design flaw in the program’s logic that should be caught during program development. The
throwing of the exception helps identify the design flaw.
Similar problems can (and often do) arise in connection with errors that
are not caught by Java. For example, suppose that your program receives
an erroneous input value, whose use would invalidate the calculation it
is making. This won’t be caught by Java. But it should be caught by your program, and an appropriate alternative here is to report the error
and terminate the program. Fixing this type of error may involve adding
routines to validate the input data before they are used in the calculation.
In short, rather than allowing an erroneous result to propagate throughout the program, it is best to terminate the program.