【发布时间】:2011-10-16 21:14:45
【问题描述】:
在以前的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
【问题讨论】:
标签: java exception final java-7