Java 中重新丟擲異常的含義是什麼?
在 catch 塊中快取異常之後,可以使用 throw 關鍵字(用於丟擲異常物件)重新丟擲該異常。
在重新丟擲異常時,可以像這樣直接丟擲,而不調整它 −
try { int result = (arr[a])/(arr[b]); System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result); } catch(ArithmeticException e) { throw e; }
也可以把它包裝在一個新的異常中並丟擲。將一個快取的異常打包在另一個異常中並丟擲時,稱為異常連結或異常包裝,透過這樣操作可以調整異常,丟擲更高層次的異常,同時保持抽象。
try { int result = (arr[a])/(arr[b]); System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result); } catch(ArrayIndexOutOfBoundsException e) { throw new IndexOutOfBoundsException(); }
示例
在以下 Java 示例中,我們的 demoMethod() 中的程式碼可能會丟擲 ArrayIndexOutOfBoundsException 和 ArithmeticException。我們在兩個不同的 catch 塊中捕獲這兩個異常。
在 catch 塊中,我們重新丟擲這兩個異常:一個被包裝在更高的異常中,另一個直接丟擲。
import java.util.Arrays; import java.util.Scanner; public class RethrowExample { public void demoMethod() { Scanner sc = new Scanner(System.in); int[] arr = {10, 20, 30, 2, 0, 8}; System.out.println("Array: "+Arrays.toString(arr)); System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)"); int a = sc.nextInt(); int b = sc.nextInt(); try { int result = (arr[a])/(arr[b]); System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result); } catch(ArrayIndexOutOfBoundsException e) { throw new IndexOutOfBoundsException(); } catch(ArithmeticException e) { throw e; } } public static void main(String [] args) { new RethrowExample().demoMethod(); } }
輸出 1
Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator(not 0) from this array (enter positions 0 to 5) 0 4 Exception in thread "main" java.lang.ArithmeticException: / by zero at myPackage.RethrowExample.demoMethod(RethrowExample.java:16) at myPackage.RethrowExample.main(RethrowExample.java:25)
輸出 2
Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator(not 0) from this array (enter positions 0 to 5) 124 5 Exception in thread "main" java.lang.IndexOutOfBoundsException at myPackage.RethrowExample.demoMethod(RethrowExample.java:17) at myPackage.RethrowExample.main(RethrowExample.java:23)
廣告