我有两段代码:
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子句中抛出新的Exception()时,我得到编译错误“Unhandled exception type Exception”.你能解释一下我为什么在第一种情况下一切都好,但在第二种情况下我得到编译错误?在这两种情况下我都抛出异常,但在第二种情况下,我创建了异常的新实例(这只是两个例子中的区别).感谢帮助.