Tuesday, 5 March 2013

How well you know Finally Block

USING FINALLY-

Finally block executes regardless of whether an exception is thrown or not , basically it is used to clean up resources which are used in code , like closing the file stream or closing the connection

Finally block override return statement also. Finally block will not execute only if JVM crashes or if you call System.exit(0) or Runtime.getRuntime.halt().
consider this simple code :

public class Test 
{
   public static void main(String[] args)
   {
    System.out.println(new Test().test());
    }

    public int test()

    {
        try

         {

        return 5;
        //throw new RuntimeException();
    
          }
         catch(Exception e )

          {
               return 3;

           }
    finally{
        return 2;

        }
    }
}

this code prints 2 instead of 5 .

but consider this sample code

public class Test 

{

 public static void main(String[] args)

{

System.out.println(new Test().test());
}





 public int test()

{

 int i =0;

try

 {

return i;

//throw new RuntimeException();

 }

catch(Exception e )

{

return 3;

}

finally{
System.out.println("setting value of i ");
i=2;

}

}

} 
What do you think the answer would be ?
The Answer is
setting value of i
0
Reason i can think of : First it goes to try block and computes the value to be returned. Now it goes to finally block , and print and change value of i now the control comes again to return statement , since the value to be returned is already computed , so it just returns 0 instead of 3. Please correct me if i am wrong


Ref StackOverFlow Thread,