The Finally Clause

Home  »  Java  »  Advance Java  »  Java Exception Handling  »  The Finally Clause


Suppose there are some action in the code that must be performed no matter what happens, that is, whather an exception is thrown or not. This is usually to free some external resource after acquiring it, to close a file after opening it, or something similar. While one could put that action both inside a catch block and outside it, that would be duplicating that same code in two different places.

Instead, one could put a copy of the code inside a special optional part of the try...cath block called finally.

Example:

The following example shows how a try...catch...finally block is structured.



The finally statement is actually useful outside exceptions, one can use it to execute cleanup code after a return, a break, or a continue inside loop.

The followning example shows how a finally statement can be used inside a method, to print the contents of the initialized array through a user-defined method.



C:\>jdk1.4\bin>javac Finally.java
C:\>jdk1.4\bin>java FinallyClause

The try...finally block causes an unusual thing to happen when the return statement is encountered. As the return statement is within the try...finally block, the statement within the finally block are executed no matter how the try block is exited. The "last number read" text always is displayed.


Download Complete Program

  -  



Java Exception Handling


Catching Java Exceptions Catching a RunTime Exception
Handling Multiple Exceptions The finally Clause
Creating User-defined Exceptions



No comments:

Post a Comment