Exceptions: When Things Go Wrong
10.2 Handling Exceptional Conditions
Traditional Error Handling
Obviously, the method in Figure 10.1 should not simply ignore the possibility that N might be 0. Figure 10.2 shows a revised version of the method, which includes code that takes action if the method’s precondition fails.
Because there is no way to compute an average of 0 elements, the revised
method decides to abort the program. Aborting the program appears to
be a better alternative than returning 0 or some other default value (like
1) as the method’s result and thereby allowing an erroneous value to
spread throughout the program. That would just compound the error.
The revised avgFirstN() method takes the traditional approach to error handling: Error-handling code is built right into the algorithm. If N
happens to be 0 when avgFirstN() is called, the following output will
be generated: