Friday 7 December 2012

Error in finally block

Leave a Comment

Java Finally Block

  • The finally block always executes immediately after try-catch block exits.
  • The finally block is executed incase even if an unexpected exception occurs.
  • The main usage of finally block is to do clean up job. Keeping cleanup code in a finally block is always a good practice, even when no exceptions are occured.
  • The run time system always executes the code within the finally block regardless of what happens in the try block. So it is the ideal place to keep cleanup code.

Finally Block Sample Code

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.myjava.exceptions;
 
public class MyFinallyBlock {
    public static void main(String[] a){
        /**
         * Exception will occur here, after catch block
         * the contol will goto finally block.
         */
        try{
            int i = 10/0;
        } catch(Exception ex){
            System.out.println("Inside 1st catch Block");
        } finally {
            System.out.println("Inside 2st finally block");
        }
        /**
         * In this case exception won't, after executing try block
         * the contol will goto finally block.
         */
        try{
            int i = 10/10;
        } catch(Exception ex){
            System.out.println("Inside 2nd catch Block");
        } finally {
            System.out.println("Inside 2nd finally block");
        }
    }
}

Example Output

Inside 1st catch Block
Inside 2st finally block
Inside 2nd finally block

If Exception Occur In Finally Block

Code:
try{

   //call to method which throws exception called SomeException

}catch(SomeException exception){
    //Handle SomeException here

} finally{
     try{
         //call to method which throws exception called OtherException
    }catch(OtherExceptionexception){
         //Handle SomeException here

    }// end of inner try-catch block


}// end of Outer try-catch-finally block
Ans: There is a possibility that exception may occur in finally block also so the program will stop itexcution abnormally if the outer catch block is not there but it will run normally if the outer catchcatches the exception which is raised in finally block.


Another Example:

public class ExceptionTest 
{
  public static void main(String args[])
  {
    try 
    {
       System.out.println("Inside Try");
     }catch(Exception e)
     {
        System.out.println("Inside catch");
      }
      finally
     {
        try
        {
            int i=10/0;
        }catch(Exception e)
          {
             System.out.println(e);
          }
      }
  }

}

exception may arise in finally block . To avoid automatic termination we can use try catch inside finally .....

0 comments:

Post a Comment