Exceptions: When Things Go Wrong

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.2 Handling Exceptional Conditions

To introduce you to handling exceptional conditions, Figure 10.1 shows a method that computes the average of the first N integers, an admittedly contrived example. We use it mainly to illustrate the basic concepts involved in exception handling. As its precondition suggests, the avgFirstN() method expects that N will be greater than 0. If N happens to be 0, an error will occur in the expression sum/N, because you cannot divide an integer by 0.

Annotation 2020-03-29 161010

Figure 10.1: Poor design. No attempt is made to guard against a divideby-zero error.

Annotation 2020-03-29 161053