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

JavaObject Oriented ProgrammingProgramming

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
raja
Published on 29-May-2019 18:14:10
Advertisements