为什么 main 方法不会捕获 catch 块中未捕获的异常
我在学习 OCPJP 认证模拟考试时想到了这个例子,
(来自 http://www.certpal.com 版本 1.6 考试第 3 部分,流程控制,问题编号 8)
public class Oak
{
public static void main(String args[])
{
try
{
Integer i =null;
i.toString();
}
catch (Exception e)
{
try
{
System.out.println("One ");
Integer i =null;
i.toString();
}
catch (Exception x)
{
System.out.println("Two ");
Integer i =null;
i.toString();
}
finally
{
System.out.println("Three ");
Integer i =null;
i.toString();
}
}
finally
{
System.out.println("Four ");
}
}
}
我我完全意识到finally块总是执行,除非有System.exit(),所以我跟踪了程序并决定它将有这样的输出
线程“main”中的一、二异常 java.lang.NullPointerException 三、线程“main”中的异常 java.lang.NullPointerException 四
然而,事实证明正确的输出是(根据现场和 Eclipse 调试)
线程“main”java.lang.NullPointerException中的一二三四异常
我不明白的是,“Two”的 catch 块中发生的异常去了哪里?
下面没有catch块,它不应该也被主线程抛出吗?因为没抓到?
I came up with this example while studying mock exams for OCPJP certification,
(from http://www.certpal.com version 1.6 exam part 3, Flow Control, Question number 8)
public class Oak
{
public static void main(String args[])
{
try
{
Integer i =null;
i.toString();
}
catch (Exception e)
{
try
{
System.out.println("One ");
Integer i =null;
i.toString();
}
catch (Exception x)
{
System.out.println("Two ");
Integer i =null;
i.toString();
}
finally
{
System.out.println("Three ");
Integer i =null;
i.toString();
}
}
finally
{
System.out.println("Four ");
}
}
}
I am fully aware that finally blocks always execute unless there is a System.exit(), so I traced the program and decided that it will have an output like this
One Two Exception in thread "main" java.lang.NullPointerException Three Exception in thread "main" java.lang.NullPointerException Four
However, it turns out the correct output is (according to the site and Eclipse debugging)
One Two Three Four Exception in thread "main" java.lang.NullPointerException
What I'm not understanding is, where did the exception which occurs in catch block with "Two" go?
There is no catch block underneath that, shouldn't it be thrown by the main thread too? Because it's not catched?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该异常实际上会丢失 - 如果finally块抛出异常,则传播过程中的任何异常都变得无关紧要,并且finally块的结果是新的异常。
同样,如果您在finally块中返回,那么整个try/catch/finally将永远不会抛出异常。
请参阅Java 语言规范的第 14.20.2 节< /a> 了解详细信息。特别是,像这样的各种位:
That exception is effectively lost - if a finally block throws an exception, any exception which was in the course of propagating becomes irrelevant, and the result of the finally block is the new exception.
Likewise if you return in a finally block, then that overall try/catch/finally will never throw an exception.
See section 14.20.2 of the Java Language Specification for details. In particular, various bits like this: