Java 中重新抛出异常是什么意思?

javaobject oriented programmingprogramming更新于 2024/3/26 13:32:17

当异常缓存在 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("数组:"+Arrays.toString(arr));
      System.out.println("从此数组中选择分子和分母(非 0)(输入位置 0 到 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println(""+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

数组:[10, 20, 30, 2, 0, 8]
从此数组中选择分子和分母(非 0)(输入位置 0 到 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

数组:[10, 20, 30, 2, 0, 8]
从此数组中选择分子和分母(非0)(输入位置0至5)
124
5
Exception in thread "main" java.lang.IndexOutOfBoundsException
   at myPackage.RethrowExample.demoMethod(RethrowExample.java:17)
   at myPackage.RethrowExample.main(RethrowExample.java:23)

相关文章


有用资源