gpt4 book ai didi

java - Java中try catch block 中可捕获异常的规则是什么?

转载 作者:行者123 更新时间:2023-12-01 17:46:21 24 4
gpt4 key购买 nike

我正在阅读 Java 语言规范,并且 this部分引起了我的注意:

It is a compile-time error if a catch clause can catch checkedexception class E1 and it is not the case that the try blockcorresponding to the catch clause can throw a checked exception classthat is a subclass or superclass of E1, unless E1 is Exception or asuperclass of Exception.

我不明白的部分在上面以粗体强调

给定以下层次结构

class A extends Exception {}
class B extends A {}
class C extends B {}

这是我的理解:

the try block corresponding to the catch clause can throw a checked exception class that is a subclass of E1

void f() {
try {
throw new C();
} catch (B b) {

}
}

编译得很好..

但是这是什么意思

the try block corresponding to the catch clause can throw a checkedexception class that is a superclass of E1

这是我的理解,它无法编译(我没想到它会编译,但 JLS 让我认为它会编译)

void f() {
try {
throw new A();
} catch (B b) { // will not compile

}
}

由于规范错误的可能性很小,您能否帮助我理解我感到困惑的部分的含义,最好能提供一个演示示例?

最佳答案

我认为理解这一点的简单方法是通过一个具体的例子:

public void doOpen(File file) throws IOException {
new FileInputStream(file);
}

请注意,该方法声明为抛出IOException,而不是其子类FileNotFoundException

现在让我们 try catch 当文件不存在时将抛出的异常:

try {
doOpen(someFile);
} catch (FileNotFoundException ex) {
// print a message
}

JLS 说:

It is a compile-time error if a catch clause can catch checked exception class E1 and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 is Exception or a superclass of Exception.

在我们示例代码的 catch 子句中,JLS 中的 E1FileNotFoundException。该方法被声明为抛出IOException。如果突出显示的子句不存在(即“或 E1 的父类(super class)”),则该捕获将不合法。但它显然应该是合法的,因为doOpen方法显然可以抛出FileNotFoundException

关于java - Java中try catch block 中可捕获异常的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54729507/

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