Can finally block be used without catch in Java?



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)
Monica Mona
Monica Mona

Student of life, and a lifelong learner


Advertisements