我正在学习异常处理,现在我有一个问题。
我认为这段代码的结果是345,但是,我不知道为什么结果是35。
即使发生异常,它不应该运行代码 System.out.println(4) 吗?
public class Six {
public static void main(String[] args) {
try {
method1();
} catch(Exception e) {
System.out.println(5);
}
}
static void method1() {
try {
method2();
System.out.println(1);
} catch(ArithmeticException e) {
System.out.println(2);
} finally {
System.out.println(3);
}
System.out.println(4);
}
static void method2() {
throw new NullPointerException();
}
}
最佳答案
在method2()
中,会抛出NullPointerException
,而在method1()
中,您只能捕获ArithmethicException
,即一个不同的异常。在这种情况下,method1()
的 catch block 不会被处理。只有finally block 会被执行,然后方法退出并将异常重新抛出给调用方法(main()
)
关于java - 异常处理方法未完成就退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40214748/