Can finally block be used without catch in Java?

Java 8Object Oriented ProgrammingProgramming

Yes, it is not mandatory to use catch block with finally. You can have to try and finally.

Example

Live Demo

public class Test {
   public static void main(String args[]) {
      int a[] = new int[2];
      try {
      } finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

Output

First element value: 6
Exception in thread "main" The finally statement is executed
java.lang.ArrayIndexOutOfBoundsException: 3
      at a5Exception_Handling.Test.main(Test.java:7)
raja
Published on 11-Jan-2018 10:27:53
Advertisements