Home  >  Article  >  Java  >  In Java, can we use try block without catch block?

In Java, can we use try block without catch block?

王林
王林forward
2023-08-19 13:29:131533browse

In Java, can we use try block without catch block?

Yes, it is possible to use a final block to try to execute without a catch block.

We know that the final block will always be executed, even if an exception occurs in the try block, unless System.exit() is used, it will always be executed.

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

Even if the method has a return type and the try block returns some value, the final block will still execute.

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

The above is the detailed content of In Java, can we use try block without catch block?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete