Thursday, 23 January 2014

BASIC finally EXCEPTION HANDLING IN JAVA

Exceptions:The finally Block 

Example to show Finally exception in java

The Finally block in java is used along with the try-catch statements.This block executed even after the unexpected exception occured.The Run time always execute the expression in finally block irrespective of the try block.  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 runtime 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.

The general form is as shown below:

try 

..... 
} catch(Exception e)

.... 
} finally 

..... 

Example:

package com.myjava.exceptions;
    public class MyFinallyBlock
    {
    public static void main(String[] a)
    {
        try
                  {
                 int i = 10/0;
                  } 
                 catch(Exception ex)
                 {
            System.out.println("Inside 1st catch Block");
               } 
          finally 
          {
            System.out.println("Inside 1st 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");
            }
    }
}

Output:

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

No comments:

Post a Comment