In java exception handling, any code that we want to must be execute put inside the
After the execution of try and catch block,
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
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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:
1 2 3 | 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;”
use finally block executes. The output is:
1 2 3 | Never Execute Inside finally After try/finally |
Note: In this program, we have not used catch block, means when an exception will be generated
Example2: write a program to demonstrate the use of finally block with try catch.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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
System.out.println(“Never Execute”);
1 2 3 | Never Execute Inside finally After try/finally |
1 2 3 | Never Execute Inside finally After try,catch & finally |