Handling Errors using Exceptions |
The next several pages show you how to build an exception handler for thewriteList()
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 thewriteList()
method. The fourth page walks through the resultingwriteList()
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 atry
block. Thetry
block is said to govern the statements enclosed within it and defines the scope of any exception handlers (established by subsequentcatch
blocks) associated with it.The catch Block(s)
Next, you associate exception handlers with atry
block by providing one or more sequentialcatch
blocks directly after thetry
block.The finally Block
Java'sfinally
block provides a mechanism which allows your method to cleanup after itself regardless of what happens within thetry
block. Use thefinally
block to close files or release other system resources.Putting It All Together
The previous sections describe how to construct thetry
,catch
, andfinally
code blocks for thewriteList()
example. Now, let's walk through the code and investigate what happens during three possible scenarios that this code presents.
Handling Errors using Exceptions |