Java 中可以有一个没有 catch 块的 try 块吗?\

javaobject oriented programmingprogramming更新于 2024/5/12 2:34:00

是的,可以使用 final 块来有一个没有 catch 块的 try 块。

众所周知,final 块始终会执行,即使 try 块中发生异常,但 System.exit() 除外,它将始终执行。

示例 1

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

输出

Try Block
Finally Block

即使方法具有返回类型并且 try 块返回某个值,final 块也始终会执行。

示例 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());
   }
}

输出

Try Block with return type
Finally Block always execute
10

相关文章