Exceptions: When Things Go Wrong

10.4 Handling Exceptions Within a Program Exception Propagation: Searching for a Catch Block

Separating Error Checking from Error Handling

As we see in the CalcAvgTest example, an important difference between Java’s exception handling and more traditional approaches is that error handling can be separated from the normal flow of execution within a program. The CalcAverage.avgFirstN() method still checks for the error and it still throws IllegalArgumentException if N does not satisfy the method’s precondition. But it does not contain code for handling the exception. The exception-handling code is located in the CalcAvgTest class.

Thus, the CalcAvgTest program creates a clear separation between the normal algorithm and the exception-handling code. One advantage of this design is that the normal algorithm is uncluttered by error-handling code and, therefore, easier to read. 

Another advantage is that the program’s response to errors has been organized into one central location. By locating the exception handler in CalcAvgTest.main(), one exception handler can be used to handle other errors of that type. For example, this catch clause could handle all IllegalArgumentExceptions that get thrown in the program. Its use of printStackTrace() will identify exactly where the exception occurred. In fact, because a Java application starts in the main() method, encapsulating all of a program’s executable statements within a single try block in the main() method will effectively handle all the exceptions that occur within a program.

Annotation 2020-03-29 165538