public static class AutoClose implements Closeable{
// 在 close 和 work 方法中均抛出异常
public void work() throws IOException {
System.out.println("work");
throw new IOException("exception in work");
}
@Override
public void close() {
System.out.println("close");
throw new RuntimeException("exception in close");
}
}
// 传统的资源关闭方法抛出的异常信息,可以看到,异常信息被覆盖
public static void main(String[] args) throws IOException {
AutoClose close = null;
try {
close = new AutoClose();
close.work();
} finally {
close.close();
}
}
// 传统方法的输出:
work
close
Exception in thread "main" java.lang.RuntimeException: exception in close
at org.example.common.Main$AutoClose.close(Main.java:27)
at org.example.common.Main.main(Main.java:36)
// 使用 try-resource-catch 语法
public static void main(String[] args) throws IOException {
try (AutoClose autoClose = new AutoClose()){
autoClose.work();
}
}
// 输出:
work
close
Exception in thread "main" java.io.IOException: exception in work
at org.example.common.Main$AutoClose.work(Main.java:21)
at org.example.common.Main.main(Main.java:40)
Suppressed: java.lang.RuntimeException: exception in close
at org.example.common.Main$AutoClose.close(Main.java:27)
at org.example.common.Main.main(Main.java:41)