【发布时间】:2017-01-03 00:40:41
【问题描述】:
我在“尝试资源”主题中遇到了一个疑问。
程序代码:
public class Suppressed_Exception_Eg03
{
public static void main(String[] args)
{
try (Wolf obj = new Wolf(); Deer obj1 = new Deer();)
{
//Both close statements are executed .
//Therefore , we see two closing stmts
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
static class Wolf implements AutoCloseable
{
@Override
public void close() throws Exception
{
System.out.println("Closing Wolf !");
throw new RuntimeException("In Wolf !");
}
}
static class Deer implements AutoCloseable
{
@Override
public void close() throws Exception
{
System.out.println("Closing Deer !");
throw new RuntimeException("In Deer !");
}
}
输出:
Closing Deer !
Closing Wolf !
In Deer !
疑问:我们都知道 Deer 类的 close 方法将首先关闭,然后是 Wolf 类。因此,Wolf 类抛出的异常应该抑制 Deer 类抛出的异常。 所以,我们应该在 catch 块中捕获 Wolf 类的异常。但是在这里我们可以在输出中看到,捕获并打印了 Deer 类的异常。有人可以解释为什么会这样吗?
【问题讨论】:
-
请通过将每个块缩进四个空格来格式化您的代码,确保同一块或同一块级别上的每一行的缩进量与其他行完全相同。是的,这是一个挑剔的要求,但同样,我们是志愿者,您希望努力让其他人更容易帮助您。
-
运行时异常将您从 try 块中引导出来。如果这是我的代码和问题,我会检查字节码。
-
.... 你还没有格式化你的代码。为什么?
-
我不明白如何格式化我的帖子。对我来说它看起来很好。