เมื่อ exception ถูกจับ (caught) ในบล็อก catch คุณสามารถโยน (re-throw) มันอีกครั้งโดยใช้คียเวิร์ด throw (ซึ่งใช้โยนอ็อบเจกต์ exception)
ขณะ re-throwing exceptions คุณสามารถโยน exception เดียวกันไปโดยไม่ปรับเปลี่ยน −
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of " + arr[a] + "/" + arr[b] + ": " + result);
} catch(ArithmeticException e) {
throw e;
}
หรือ ห่อหุ้มมันใน exception ใหม่และโยน เมื่อคุณห่อ exception ที่จับได้ไว้ใน exception อีกตัวแล้วโยน เรียกว่า exception chaining หรือ exception wrapping ด้วยวิธีนี้คุณสามารถปรับ exception ได้ โยน exception ระดับสูงกว่าพร้อมรักษาการนามธรรม (abstraction)
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 เราจับสอง exception นี้ในสองบล็อก catch ที่ต่างกัน
ในบล็อก catch เรา re-throw ทั้งสอง exception หนึ่งตัวห่อใน exception ระดับสูงกว่า อีกตัวโยนโดยตรง
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();
}
}
Output 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)
Output 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)