java catch块,关于java:如何确定哪个catch块首先出现?

接下来如何确定捕获块?

try{

int a[]=new int[5];

a[5]=30/0;

}

catch(ArithmeticException e){System.out.println("task1 is completed");}

catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}

catch(Exception e){System.out.println("common task completed");}

我知道派生类排在第一位,基类紧随其后。 类ArithmeticException和ArrayIndexOutOfBoundsException来自:

为什么ArithmeticException放在首位?

捕获异常时顺序为何重要的可能重复?

"为什么首先放置ArithmeticException?" 没理由。 只要ArithmeticException和ArrayIndexOutOfBoundsException都在Exception之前,它们的顺序就可以。

它们按照您提供它们的顺序进行了测试:第一个catch类型是所抛出异常的类,或者它的超类是所使用的。 JLS§14.20.1中对此进行了描述:

If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

If the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed, and then there is a choice:

If that block completes normally, then the try statement completes normally.

If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the try statement completes abruptly because of a throw of the value V.

继续您的问题...

Why ArithmeticException is placed first?

因为那是该代码的作者想要做的。在该代码中,ArithmeticException或IndexOutOfBoundsException的catch放在第一位无关紧要,因为它们是类型层次结构中的不同分支。没有抛出异常与它们两个都兼容,因此前两个catch块的顺序无关紧要。但是,第三个块必须在末尾,因为ArithmeticException和IndexOutOfBoundsException与Exception分配兼容。

您可以交换提到的两个catch子句,结果将相同。

由于ArithmeticException与ArrayIndexOutOfBoundsException之间没有直接的层次关系,所以没有关系。异常控件从try块线性流出。

另外,请确保您执行的调试打印中包含一些语义,而不仅仅是"任务1完成" ...如果这只是测试代码段而不是长期项目的一部分,请忽略上述声明。

从任何静态意义上讲,都不将ArithmetcException放在首位。您观察到的行为更多地与赋值表达式的求值有关:在赋值中,右手侧先于左手侧被完全求值。

因此,在尝试错误的数组访问之前,尝试除以零(并抛出相关异常)。

因此,您的代码不会抛出与数组相关的异常,而这些访问超出了范围。

它是顺序和类型匹配的组合。

执行与异常类型匹配的第一个catch块。

我相信这是第一个匹配的,而不是"最具体的"。

例如,如果您首先具有catch(Exception e),其余的甚至都不会得到关注。

这个应该是一个评论

好吧,当我获得足够的声誉以在原始问题上添加评论时,我就会这样做。 有点屈服于指责某人没有代表时不发表评论。 我必须提供首先获得选票的答案。

我做到了。 我能理解你的痛苦! 我只是评论了一下,以便您可以对其进行更详尽和更详尽的说明,以便做出回答。 如果您这样做,我会投票赞成!

抱歉。 只是Im 2/2被"评分"为回答而不是评论。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值