Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The final step in setting up an exception handler is to clean up before allowing control to be passed to a different part of the program. You do this by enclosing the clean up code within afinally
block. Thefinally
block is optional and provides a mechanism to clean up regardless of what happens within thetry
block. Use thefinally
block to close files or to release other system resources.The
try
block of thewriteList
method that you�ve been working with here opens aPrintWriter
. The program should close that stream before exiting thewriteList
method. This poses a somewhat complicated problem becausewriteList
�stry
block can exit in one of three ways.The runtime system always executes the statements within the
- The
new FileWriter
statement fails and throws anIOException
.- The
victor.elementAt(i)
statement fails and throws anArrayIndexOutOfBoundsException
.- Everything succeeds and the
try
block exits normally.finally
block regardless of what happens within thetry
block. So it�s the perfect place to per�form cleanup.The following
finally
block for thewriteList
method cleans up and closes the PrintWriter.In thefinally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } }writeList
example, you could provide for cleanup without the intervention of afinally
block. For example, you could put the code to close thePrintWriter
at the end of the try block and again within the exception handler forArrayIndexOutOfBoundsException
, as shown here:However, this duplicates code, thus making the code difficult to read and error prone if you later modify it. For example, if you add to thetry { ... out.close(); // don't do this; it duplicates code } catch (FileNotFoundException e) { out.close(); // don't do this; it duplicates code System.err.println("Caught: FileNotFoundException: " + e.getMessage()); throw new RuntimeException(e); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }try
block code that can throw a new type of exception, you have to remember to close thePrintWriter
within the new exception handler.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.