19.5. Recursive Helper Methods

 
[Page 589 ( continued )]

17.5. The finally Clause

Occasionally, you may want some code to be executed regardless of whether an exception occurs or is caught. Java has a finally clause that can be used to accomplish this objective. The syntax for the finally clause might look like this:

   try   {   statements; }   catch   (TheException ex) {   handling ex; }   finally   {   finalStatements; } 

The code in the finally block is executed under all circumstances, regardless of whether an exception occurs in the try block or is caught. Consider three possible cases:

  • If no exception arises in the try block, finalStatements is executed, and the next statement after the try statement is executed.

  • If one of the statements causes an exception in the try block that is caught in a catch block, the other statements in the try block are skipped , the catch block is executed, and the finally clause is executed. If the catch block does not rethrow an exception, the next statement after the try statement is executed. If it does, the exception is passed to the caller of this method.

  • If one of the statements causes an exception that is not caught in any catch block, the other statements in the try block are skipped, the finally clause is executed, and the exception is passed to the caller of this method.

  • The finally block executes even if there is a return statement prior to reaching the finally block.


    [Page 590]

Note

The catch block may be omitted when the finally clause is used.


A common use of the finally clause is in I/O programming. To ensure that a file is closed under all circumstances, you may place a file closing statement in the finally block, as shown in Listing 17.6.

Listing 17.6. FinallyDemo.java
 1   public class   FinallyDemo {  2   public static void   main(String[] args) {  3      java.io.PrintWriter output =   null   ;  4  5    try   {  6  // Create a file  7  output =   new   java.io.Printwriter(   "text.txt"   );  8  9  // Write formatted output to the file  10  output.println(   "Welcome to Java"   );  11      } 12    catch   (java.io.IOException ex) {  13        ex.printStackTrace(); 14      } 15    finally   {  16  // Close the file  17    if   (output !=   null   ) output.close();  18      } 19    } 20  } 

The statements in lines 7 and 10 may throw an IOException , so they are placed inside a try block. The statement output.close() closes the PrintWriter object output in the finally block. This statement is executed regardless of whether an exception occurs in the try block or is caught.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net