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)

更新日期:2019 年 11 月 1 日

5K+ 浏览量

开启您的 职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.