Java 的 code form 到底會不會阻塞


finally 塊緊接在 try 塊或 catch 塊後面。無論是否發生異常,finally 塊內的程式碼始終都會執行。

方法中的 return 語句也不會阻止 finally 塊執行。

示例

在以下 Java 程式中,我們仍然在 try 塊末尾使用 return 語句,finally 塊中的語句會執行。

 即時演示

public class FinallyExample {
   public static void main(String args[]) {
      int a[] = new int[2];
      try {
         System.out.println("Access element three :" + a[3]);
         return;
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown :" + e);
      } finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

輸出

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

避免 finally 塊的唯一方法

但在異常發生時,如果仍想要強制執行,唯一的方法是在 catch 塊末尾(就在 finally 塊之前)呼叫 System.exit(0) 方法。

示例

 即時演示

public class FinallyExample {
   public static void main(String args[]) {
      int a[] = {21, 32, 65, 78};
      try {
         System.out.println("Access element three :" + a[5]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown :" + e);
         System.exit(0);
      } finally {
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

輸出

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 5

更新日期:2019 年 9 月 12 日

146 次瀏覽

開啟你的 職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.