What is the finally block in Java?

Java 8Object Oriented ProgrammingProgramming

The finally block follows a try block or a catch block. A finally block of code forever executes, no matter prevalence of an Exception.

Example

Live Demo

public class ExcepTest {
   public static void main(String args[]) {
      int a[] = new int[2];
      try {
         System.out.println("Access element three :" + a[3]);
      } 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
raja
Published on 11-Jan-2018 10:20:19
Advertisements