It is not a matter of IF but WHEN things will go wrong in a computer program. Sometimes there are bugs, errors of one form or another. There are also unforeseen use cases. You can never assume a computer program is perfect. Exception-Handling helps us to catch erroneous events and devise means of correcting them. We discuss this topic here since exception-handling can take more code than should be put into the main line of execution. In such cases, a method in an exception-handling class should be called. Exception handling mechanisms allow a program to continue executing, instead of terminating it abruptly, even if an error occurs in the program.
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.