Handling Errors using Exceptions |
The next several pages show you how to build an exception handler for thewriteList()
method described in The ListOfNumbers 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 morecatch
blocks directly after thetry
block.The finally Block
Java'sfinally
block provides a mechanism that allows your method to clean up 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 scenarios.
Handling Errors using Exceptions |