Can we have a try block without a catch block in Java?


Yes, It is possible to have a try block without a catch block by using a final block.

As we know, a final block will always execute even there is an exception occurred in a try block, except System.exit() it will execute always.

Example 1

public class TryBlockWithoutCatch {
   public static void main(String[] args) {
      try {
         System.out.println("Try Block");
      } finally {
         System.out.println("Finally Block");
      }
   }
}

Output

Try Block
Finally Block

A final block will always execute even though the method has a return type and try block returns some value.

Example 2

public class TryWithFinally {
   public static int method() {
      try {
         System.out.println("Try Block with return type");
         return 10;
      } finally {
         System.out.println("Finally Block always execute");
      }
   }
   public static void main(String[] args) {
      System.out.println(method());
   }
} 

Output

Try Block with return type
Finally Block always execute
10 

Updated on: 21-Nov-2023

23K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements