|      | 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. Do this by enclosing the cleanup code within afinallyblock. Thefinallyblock is optional and provides a cleanup mechanism regardless of what happens within thetryblock. Use thefinallyblock to close files or to release other system resources.The
tryblock of thewriteListmethod that you've been working with here opens aPrintWriter. The program should close that stream before exiting thewriteListmethod. This poses a somewhat complicated problem becausewriteList'stryblock can exit in one of three ways.The runtime system always executes the statements within the
- The
new FileWriterstatement fails and throws anIOException.- The
victor.elementAt(i)statement fails and throws anArrayIndexOutOfBoundsException.- Everything succeeds and the
tryblock exits normally.finallyblock regardless of what happens within thetryblock. So it's the perfect place to perform cleanup.The following
finallyblock for thewriteListmethod cleans up and then closes thePrintWriter.In thefinally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } }writeListexample, you could provide for cleanup without the intervention of afinallyblock. For example, you could put the code to close thePrintWriterat the end of thetryblock and again within the exception handler forArrayIndexOutOfBoundsException, as follows.However, this duplicates code, thus making the code difficult to read and error-prone should you modify it later. For example, if you add code that can throw a new type of exception 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()); }tryblock, you have to remember to close thePrintWriterwithin 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.