Turn Desktop View Off
by Dinesh Thakur

If an exception occurs inside a try block and there is no matching catch block, the method terminates without further executing any lines of code from that method. For example, suppose you may want to close a file that has been opened even if your program could not read from the file for some reason. In other words, you want to close the file irrespective whether the read is successful or not. If you want that some lines of code must be executed regardless of whether or not there is matching catch block, put those lines inside the finally block.

The finally block is used to release system resources and perform any cleanup required by the code in the try block. The finally block consist of finally keyword followed by the code enclose in curly braces. Just like a catch block, a finally block is associated with a particular try block and must appear after the last catch block. If there are no catch blocks then you can place the finally block immediately after the try block.

The general from of a try statement with finally block is

try

{

       //statement that can throw exceptions

}

catch(exception_type identifier)

{

      //statements executed after exception is thrown

}

finally

{

//statements which are executed regardless of whether or not

//exceptions are thrown

}

Let us consider three cases when the try-catch block executes only with the finally block.

Case A: If the try block succeeds (i.e. no exception is thrown), the flow of control reaches the end of try block and proceeds to the finally block by skipping over the catch blocks. When the finally block completes, the rest of the method continues on.

Case B: If a try block fails (i.e. exception is thrown), the flow control immediately move to the appropriate catch block. When the catch block completes, the finally block runs. When the finally block completes, the rest of the method continues on.

Case C: If the try or catch block has a return statement, the finally block will still get executed before control transfers to its new destination.

Now let us consider a example that demonstrates the use of finally block

public class FinallyBlock 


     public static void main(String[] args)
     {
        int x=12,y=0,z;
        try
        {
         z=x/y;
         System.out.println(x + " / " + y +" = " + z);
        }
        catch(ArithmeticException e)
        {
              System.out.println("Divide by Zero");
        }
        finally
        {
              System.out.println("Inside Finally Block");
         }
              System.out.println("End of Main Method");
      }
}

Finally Block in Java with Example