gpt4 book ai didi

java - 重新抛出前面的 catch block 中处理的异常

转载 作者:太空宇宙 更新时间:2023-11-04 06:34:23 25 4
gpt4 key购买 nike

在 Oracle 官方网站上写入 (http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html#rethrow)

In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:

-The try block is able to throw it.

-There are no other preceding catch blocks that can handle it.

-It is a subtype or supertype of one of the catch clause's exception parameters.

请专注于第二点(前面没有其他 catch block 可以处理它。)

研究以下代码:

static private void foo() throws FileNotFoundException  {
try {
throw new FileNotFoundException();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
throw e;
}
}

这段代码编译良好。根据我的观点,在阅读上述文章的引用后,我希望看到编译器会验证它,并且我会收到编译器错误。

我是否理解错了第二点?

最佳答案

这完全没问题,因为 FileNotFoundException 是从 IOException 派生的,并且因为您从不太具体到更具体,所以不应该有任何问题。

<小时/>

编辑:

static private void foo() throws FileNotFoundException  {
try {
throw new FileNotFoundException();
} catch (IOException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
throw e;
}
}

关于java - 重新抛出前面的 catch block 中处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25625317/

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