java 链式异常,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;

}

链接异常

您还可以将捕获到的异常包装在新异常中,然后将其抛出(在catch块中)。这样做时,第一个异常负责第二个异常,即,一个异常导致另一个。

因此,当您将缓存的异常包装在另一个异常中并引发异常时,这称为异常链接或异常包装,通过执行此操作,您可以调整异常,并抛出更高级别的异常来维护抽象。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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值