Home » java » Finally Keyword in Java

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.

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:

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:

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.

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:

Managed by MochaHost - Fast & Easy WordPress Hosting