Finally Keyword in Java

In java exception handling, any code that we want to must be execute put inside the finally block.

After the execution of try and catch block, finally block executes. try block must be used with either catch or finally, or with both.

Normally when exception occurs then further programs never executes. 

But either exception occurs or not, in both condition finally block executes.

Example1:  write a program to demonstrate the use of finally block with only try.

public class FinallyDemo {
    public static void main(String args[]) {
        int a[] = new int[10];
        try {
            a[100] = 20; 
         // a[5] = 10;
            System.out.println("Never Execute");
        } finally {
            System.out.println("Inside finally");
        }
        System.out.println("After try/finally ");
    }
}

In the above program, we use two conditions, in the first condition we set array a is “a[100] = 20;”

 than exception occurs the following two lines will never execute

System.out.println(“Never Execute”);

System.out.println(“After try/finally “);

But finally block executes. And output is:

Inside finally
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at FinallyDemo.main(FinallyDemo.java:5)

In the second condition, we set array a is “a[5] = 10;”  than there is no exception occurs.

use finally block executes. The output is:

Never Execute
Inside finally
After try/finally 

Note: In this program, we have not used catch block, means when an exception will be generated then the program will never execute but finally must be executed .

Example2: write a program to demonstrate the use of finally block with try catch.

public class FinallyDemo1 {
    public static void main(String args[]) {
        int a[] = new int[10];
        try {
            a[100] = 20; // (2)  a[5] = 10;
            System.out.println("Never Execute");
        } catch (ArrayIndexOutOfBoundException e) {
            System.out.println("Exception =" + e);
        } finally {
            System.out.println("Inside finally");
        }
        System.out.println("After try,catch and finally ");
    }
}

In the above program, we uses two condition, in the first condition we set array a is “a[100] = 20;”  than exception occurs the following  line will not execute

            System.out.println(“Never Execute”);

and exception is thrown which is caught bycatch(ArrayIndexOutOfBoundException  e)” after the catch rest of the program will execute. and the output is:

Never Execute
Inside finally
After try/finally 
Never Execute
Inside finally
After try,catch & finally