Home > Java > javaTutorial > body text

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

王林
Release: 2023-08-19 13:29:13
forward
1541 people have browsed it

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");
      }
   }
}
Copy after login

Output

Try Block
Finally Block
Copy after login

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());
   }
}
Copy after login

Output

Try Block with return type
Finally Block always execute
10
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template