尝试使用资源

时间:2016-08-26 10:55:15

标签: java 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类的close方法将首先关闭,后面将是Wolf类。因此,Wolf类抛出的异常应该抑制Deer类抛出的异常。 所以,我们应该抓住狼类' catch块中的异常。但是在这里我们可以看到输出中的鹿类'捕获并打印异常。有人可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:5)

规范说:

  

资源以与初始化资源相反的顺序关闭。   仅当资源初始化为非空值时才关闭资源。关闭一个资源的例外不会阻止关闭其他资源。如果先前由初始化程序,try块或关闭资源引发异常,则会抑制此类异常。

代码中的第一个异常(Deer)未被抑制,因为之前没有抛出异常。然后,关闭下一个资源(Wolf),但这次来自Wolf的异常被抑制。