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: | ||
|
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