Does code form Java finally block


The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.

The return statement in the method too does not stop the finally block from getting executed.

Example

In the following Java program we are using return statement at the end of the try block still, the statements in the finally block gets executed.

 Live Demo

public class FinallyExample {
   public static void main(String args[]) {
      int a[] = new int[2];
      try {
         System.out.println("Access element three :" + a[3]);
         return;
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown :" + e);
      } finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

Output

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

Only way to avoid the finally block

Still if you want to do it forcefully when an exception occurred, the only way is to call the System.exit(0) method, at the end of the catch block which is just before the finally block.

Example

 Live Demo

public class FinallyExample {
   public static void main(String args[]) {
      int a[] = {21, 32, 65, 78};
      try {
         System.out.println("Access element three :" + a[5]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown :" + e);
         System.exit(0);
      } finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

Output

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 5

Updated on: 12-Sep-2019

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements