เมื่อข้อยกเว้นถูกแคชในบล็อก 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)