Thefinallyblock always executes when thetryblock exits. This ensures that thefinallyblock is executed even if an unexpected exception occurs. Butfinallyis useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by areturn,continue, orbreak. Putting cleanup code in afinallyblock is always a good practice, even when no exceptions are anticipated.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
vector.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.
Important: Thefinallyblock is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in afinallyblock to insure that resource is always recovered.