gpt4 book ai didi

java - 尝试资源

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:06:28 26 4
gpt4 key购买 nike

我在“尝试资源”主题中遇到了一个疑问。

程序代码:

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类的close方法会先关闭。因此,Wolf 类抛出的异常应该抑制 Deer 类抛出的异常。所以,我们应该在 catch block 中捕获 Wolf 类的异常。但是在这里我们可以在输出中看到,捕获并打印了 Deer 类的异常。有人可以解释这是为什么吗?

最佳答案

规范说:

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 的异常被抑制了。

关于java - 尝试资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39164634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com