【发布时间】:2016-12-08 10:27:15
【问题描述】:
我正在 Java 8 中的一个简单应用程序中使用 try-with-resources。 我正在实现 AutoCloseable 接口并覆盖 close() 方法。 在我的一个实现 AutoCloseable 的类中,我在 close() 方法中抛出了一个异常,该方法将作为 Suppressed Exception 工作。在我的主要方法中,我发现了异常。但是 close 方法的异常并没有被抑制。由于捕获了一般异常,因此该异常被捕获在 catch 块中。
这是我的代码:
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.
为什么 close 方法中的异常没有被抑制?
【问题讨论】:
-
不要将“抑制”与“吞咽”混为一谈