gpt4 book ai didi

Java 7 - 带有最终异常的精确重新抛出

转载 作者:IT老高 更新时间:2023-10-28 20:40:59 24 4
gpt4 key购买 nike

在以前的java版本中,重新抛出异常被视为抛出catch参数的类型。

例如:

public static void test() throws Exception{
DateFormat df = new SimpleDateFormat("yyyyMMdd");
try {
df.parse("x20110731");
new FileReader("file.txt").read();
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
throw e;
}
}

在 Java 7 中,如果您声明异常 final,您可以更准确地了解所引发的异常:

//(doesn't compile in Java<7)
public static void test2() throws ParseException, IOException{
DateFormat df = new SimpleDateFormat("yyyyMMdd");
try {
df.parse("x20110731");
new FileReader("file.txt").read();
} catch (final Exception e) {
System.out.println("Caught exception: " + e.getMessage());
throw e;
}
}

我的问题:文档说我需要声明异常final。但如果我不这样做,上面的代码仍然可以编译和工作。我错过了什么吗?

引用资料:

Project Coin: multi-catch and final rethrow
Add more flexible checking for rethrown exceptions

最佳答案

相信我看到 Josh Bloch 的一条推文说“最终”限制已被取消。我会看看能不能找到一篇关于它的帖子,但我怀疑你阅读的任何“早期”文档现在都不准确。

编辑:我找不到确切的“它已更改”帖子,但 Java 7 documentation states显示了一个例子,它 not 是最终的。它谈到异常变量是隐式当一个catch block 声明了多个类型时,但这有点分开。

编辑:我现在找到了我的困惑的根源,但它是一个内部邮件列表帖子 :( 无论如何,它不必被声明为 final,但我相信编译器会将其视为 隐式 final - 就像在 multi-catch 场景中一样。

关于Java 7 - 带有最终异常的精确重新抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6889270/

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