What is the finally block in Java?



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
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements