如何在 Java 中重新丟擲異常?
有時候我們需要在 Java 中重新丟擲異常。如果一個 catch 程式碼塊無法處理其捕捉到的特定異常,我們可以重新丟擲該異常。rethrow 表示式會導致最初丟擲的物件被重新丟擲。
由於異常已經在 rethrow 表示式出現的範圍內被捕獲,因此它被重新丟擲到下一個包含的 try 程式碼塊。因此,它無法由重新丟擲表示式出現的範圍內的 catch 塊處理。包含的 try 程式碼塊的任何 catch 塊都有機會捕獲異常。
語法
catch(Exception e) { System.out.println("An exception was thrown"); throw e; }
示例
public class RethrowException { public static void test1() throws Exception { System.out.println("The Exception in test1() method"); throw new Exception("thrown from test1() method"); } public static void test2() throws Throwable { try { test1(); } catch(Exception e) { System.out.println("Inside test2() method"); throw e; } } public static void main(String[] args) throws Throwable { try { test2(); } catch(Exception e) { System.out.println("Caught in main"); } } }
輸出
The Exception in test1() method Inside test2() method Caught in main
廣告