|
|
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 afinallyblock. Thefinallyblock is optional and provides a mechanism to clean up 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 closes the PrintWriter.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 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()); }tryblock code that can throw a new type of exception, 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.