在Java8中的一个简单应用程序中,我正在使用“使用资源进行尝试”,我正在实现AutoCloseable接口,而不是使用close()方法。在实现AutoCloseable的类中,我在close()方法中抛出一个异常,该方法将作为抑制的异常工作。在我的主要方法中,我发现了异常。但是,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.为什么这里的盗梦在近距离的方法不被压制?
发布于 2016-12-08 12:15:53
我认为你必须再读一遍关于试着用资源的文章。
只有在有多个例外的情况下,异常才会被抑制。此外,还指定了抑制异常的时间和类型,如本例中所示:
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)https://stackoverflow.com/questions/41037135
复制相似问题