Java 中是否可以有無 `catch` 塊的 `try` 塊?


可以,透過使用`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

`final` 塊總是會執行,即使方法有返回值型別且 `try` 塊返回一些值。

示例 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 

更新於: 2023-11-21

2.9 萬+ 瀏覽量

開啟你的職業生涯

完成課程以獲得認證

開始
廣告