gpt4 book ai didi

java - 异常捕获层次结构流程

转载 作者:行者123 更新时间:2023-12-01 08:05:09 25 4
gpt4 key购买 nike

我正在 java 中实现带有多个异常的异常处理。

请看以下场景:函数 f1 抛出异常 e1、e2、e3 和 e4函数 f2 捕获这些。

现在我想通过catch(Exception e1 and e2)显式地捕获e1,e2,并且其他异常应该通过catch(Exception e)在同一个 block 中捕获所以e1和e2是特例,其他都是一般异常。

那么下面的方法会起作用吗?

try{
//some work`
} catch(ExceptionType1 e1) {
//do some special logging
} catch (ExceptionType2 e2) {
//do some special logging
} catch(Exception e) {
//do general logging for other exceptions
}

我的问题是ExceptionType1(e1)是否也会被Exception e捕获?

最佳答案

规范 writes :

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.

因此,最多会执行一个catch block 。

关于java - 异常捕获层次结构流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22339052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com