gpt4 book ai didi

Java多个catch block 中 `e`变量的类型是什么?

转载 作者:行者123 更新时间:2023-12-02 11:36:16 25 4
gpt4 key购买 nike

Java 提供了在单个 catch block 中捕获多个异常的功能。但这让我很困惑。我怎么知道这个 block 中捕获了哪个异常?通常java中的变量只有一种类型。那么如何e变量的类型太多?

示例

try {
// codes
// ...
// ..
// .
} catch(InturreptedException | FileNotFoundException | AnotherException e) {
// how can I know what the type of `e` is ?
}

最佳答案

e 类型是 multi-catch 子句中列出的可抛出类型中最具体的常见父类(super class)型。

如果AnotherExceptionException的某种子类型,那么在您的情况下它将是Exception,因为InterruptedExceptionFileNotFoundExceptionException 作为最具体的常见父类(super class)型。

更准确地说,规范的内容如下:

The declared type of an exception parameter that denotes its type as a union with alternatives D1 | D2 | ... | Dn is lub(D1, D2, ..., Dn) (§15.12.2.7).

lub 是 Java 语言规范第 4.10.4 节中定义的“最小上限”: https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html

关于Java多个catch block 中 `e`变量的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48913110/

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