我有两段代码:
class PreciseRethrow {
public static void main(String[] str) {
try {
foo();
} catch (NumberFormatException ife) {
System.out.println(ife);
}
}
static private void foo() throws NumberFormatException {
try {
int i = Integer.parseInt("ten");
} catch (Exception e) {
throw e;
}
}
}
并且:
class PreciseRethrow {
public static void main(String[] str) {
try {
foo();
} catch (NumberFormatException ife) {
System.out.println(ife);
}
}
static private void foo() throws NumberFormatException {
try {
int i = Integer.parseInt("ten");
} catch (Exception e) {
throw new Exception();
}
}
}
在第二种情况下,当我在catch子句中抛出新的异常(new Exception())时,我得到了编译错误“Unhandled exception type Exception”。您能解释一下为什么第一种情况一切正常,但第二种情况却出现了编译错误吗?在两种情况下,我都抛出了异常,但在第二种情况下,我创建了一个新的异常实例(这是这两个示例之间唯一的区别)。感谢您的帮助。