尝试资源
try with Resources
我在 "Try with Resources" 主题中遇到了一个疑问。
程序代码:
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 class 的 close 方法将首先关闭,然后是 Wolf class 的关闭方法。因此,Wolf class 抛出的异常应该抑制 Deer class 抛出的异常。
所以,我们应该在 catch 块中捕获 Wolf class' 异常。但是在这里我们可以在输出中看到,捕获并打印了 Deer class' 异常。有人可以解释这是为什么吗?
规范说:
Resources are closed in the reverse order from that in which they were initialized.
A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.
您的代码中的第一个异常 (Deer
) 没有被抑制,因为之前没有抛出异常。然后,关闭下一个资源 (Wolf
),但这次来自 Wolf
的异常被抑制了。
我在 "Try with Resources" 主题中遇到了一个疑问。
程序代码:
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 class 的 close 方法将首先关闭,然后是 Wolf class 的关闭方法。因此,Wolf class 抛出的异常应该抑制 Deer class 抛出的异常。 所以,我们应该在 catch 块中捕获 Wolf class' 异常。但是在这里我们可以在输出中看到,捕获并打印了 Deer class' 异常。有人可以解释这是为什么吗?
规范说:
Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.
您的代码中的第一个异常 (Deer
) 没有被抑制,因为之前没有抛出异常。然后,关闭下一个资源 (Wolf
),但这次来自 Wolf
的异常被抑制了。