Sunday, May 25, 2014

What Final Finlize and Finally does extra in Java

Finally


There are 4 potential scenarios here:

1. The try block runs to the end, and no exception is 
thrown.  In this scenario, the finally block will be 
executed after the try block.

2. An exception is thrown in the try block, which is
then caught in one of the catch blocks.  In this scenario, 
the finally block will execute right after the catch block 
executes.

3. An exception is thrown in the try block and there's 
no matching catch block in the method that can catch 
the exception.  In this scenario, the call to the method 
ends, and the exception object   is thrown to the enclosing 
method - as in the method in which the   try-catch-finally
blocks reside.  But, before the method ends, the finally 
block is executed.

4.  Before the try block runs to completion it returns to 
wherever the method was invoked.  But, before it returns 
to the invoking method, the code in the finally block is still 
executed.  So, remember that the code in the finally  block 
will still be executed even if there is a return 
statement somewhere in the try block.

Program

public void someMethod{
   Try {
   // some code
   }

   Catch(Exception x) {
   // some code
   }

   Catch(ExceptionClass y) {
   // some code
   }

   Finally{
   //this code will be executed whether or not an exception 
   //is thrown or caught
   }
}