在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(); }
從已檢查異常丟擲未檢查異常
是的,我們可以捕獲編譯時異常(已檢查)並在catch塊中將其包裝在執行時異常(未檢查)中並重新丟擲。但是,由於我們使用已檢查異常重新丟擲,因此我們需要將其包裝在隱式try-catch對中,或者使用throws子句跳過處理它。
示例
在下面的Java示例中,我們建立了一個名為SampleException的使用者定義(已檢查)異常。
我們顯示一個包含6個元素的整數陣列,並允許使用者選擇兩個值的索引並對選定的數字進行除法運算。在選擇索引時,使用者可能會使用超出陣列長度的索引值,這會導致ArrayIndexOutOfBoundsException,這是一個未檢查異常。
在catch塊中,我們透過將其包裝在上面建立的Sample異常(已檢查)中來重新丟擲此物件。
import java.util.Arrays; import java.util.Scanner; class SampleException extends Exception { SampleException(String msg){ super(msg); } } public class Rethrow { public void demoMethod() { Scanner sc = new Scanner(System.in); int[] arr = {10, 20, 30, 2, 5, 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) { try { throw new SampleException("This is a checked exception"); } catch (SampleException e1) { System.out.println("Checked exception in the catch block"); } } } public static void main(String [] args) { new Rethrow().demoMethod(); } }
輸出
Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator(not 0) from this array (enter positions 0 to 5) 25 24 Checked exception in the catch block
廣告