当将异常缓存在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();
}
}
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)
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)