Previous | Next | Trail Map | Writing Java Programs | Handling Errors using Exceptions


Catching and Handling Exceptions

The next several pages show you how to build an exception handler for the writeList() method in the example program described in The Example. The first three pages listed below describe three different components of an exception handler and show how those components can be used in the writeList() method. The fourth page walks through the resulting writeList() method and analyzes what occurs within the example code during various scenarios.

The try Block

The first step in writing any exception handler is putting the Java statements within which an exception can occur into a try block. The try block is said to govern the statements enclosed within it and defines the scope of any exception handlers (established by subsequent catch blocks) associated with it.

The catch Block(s)

Next, you associate exception handlers with a try block by providing one or more sequential catch blocks directly after the try block.

The finally Block

Java's finally block provides a mechanism which allows your method to cleanup after itself regardless of what happens within the try block. Use the finally block to close files or release other system resources.

Putting It All Together

The previous sections describe how to construct the try, catch, and finally code blocks for the writeList() example. Now, let's walk through the code and investigate what happens during three possible scenarios that this code presents.


Previous | Next | Trail Map | Writing Java Programs | Handling Errors using Exceptions