AutoCloseable close()方法异常未被抑制

时间:2016-12-08 10:27:16

标签: java-8 try-with-resources

我正在使用Java 8中的简单应用程序中的try-with-resources。 我正在实现AutoCloseable接口并使用close()方法。 在我的一个实现AutoCloseable的类中,我在close()方法中抛出一个异常,它将作为Suppressed Exception。在我的主要方法中,我正在捕捉异常。但是close方法的例外并没有被抑制。由于一般的例外被捕获,该异常正被抓住了。

这是我的代码:

public class TryWithResourcesExample {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try (Lion lion = new Lion(); Tiger tiger = new Tiger()) {

            lion.hunt();
            tiger.hunt();

        } catch (Exception e) {
            System.out.println("Got Simple Exception = "+e);
            for(Throwable t: e.getSuppressed())
            {
                System.out.println("Got Suppressed Exception = "+t);
                t.printStackTrace();
            }
        } finally {
            System.out.println("Finally.");
        }
    }

}

class Tiger implements AutoCloseable {
    public Tiger() {
        System.out.println("TIGER is OPEN in the wild.");
    };

    public void hunt() throws Exception {
        //throw new Exception("DeerNotFound says Tiger!");
    }

    public void close() throws Exception {
        System.out.println("Tiger is CLOSED in the cage.");
    }
}

class Lion implements AutoCloseable {

    public Lion() {
        System.out.println("LION is OPEN in the wild.");
    }

    public void hunt() throws Exception {
        //throw new Exception("DeerNotFound says Lion!");
    }

    public void close() throws Exception {
        System.out.println("LION is CLOSED in the cage.");
        throw new Exception("Lion Unable to close the cage!");
    }
}

这是我的输出:

LION is OPEN in the wild.
TIGER is OPEN in the wild.
Tiger is CLOSED in the cage.
LION is CLOSED in the cage.
Got Simple Exception = java.lang.Exception: Lion Unable to close the cage!
Finally.

为什么这里的封闭方法中的异常没有被抑制?

1 个答案:

答案 0 :(得分:4)

我认为您必须再次阅读有关try-with-resource的文章。

仅当存在多个例外时才会禁止例外。此外,还会指定一个订单,以及在此示例中抑制哪些异常:

public class Test {
  public static void main(String... args) {
    try (ExceptionResource test = new ExceptionResource()) {
      test.work();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

class ExceptionResource implements AutoCloseable {

  public void work() throws Exception {
    throw new Exception("Thrown in 'run'");
  }

  @Override
  public void close() throws Exception {
    throw new Exception("Thrown in 'close'");
  }
}

结果:

java.lang.Exception: Thrown in 'run'
at test.ExceptionResource.work(Test.java:16)
at test.Test.main(Test.java:6)
Suppressed: java.lang.Exception: Thrown in 'close'
    at test.ExceptionResource.close(Test.java:21)
    at test.Test.main(Test.java:7)