1. public static class AutoClose implements Closeable{
    2. // 在 close 和 work 方法中均抛出异常
    3. public void work() throws IOException {
    4. System.out.println("work");
    5. throw new IOException("exception in work");
    6. }
    7. @Override
    8. public void close() {
    9. System.out.println("close");
    10. throw new RuntimeException("exception in close");
    11. }
    12. }
    13. // 传统的资源关闭方法抛出的异常信息,可以看到,异常信息被覆盖
    14. public static void main(String[] args) throws IOException {
    15. AutoClose close = null;
    16. try {
    17. close = new AutoClose();
    18. close.work();
    19. } finally {
    20. close.close();
    21. }
    22. }
    23. // 传统方法的输出:
    24. work
    25. close
    26. Exception in thread "main" java.lang.RuntimeException: exception in close
    27. at org.example.common.Main$AutoClose.close(Main.java:27)
    28. at org.example.common.Main.main(Main.java:36)
    29. // 使用 try-resource-catch 语法
    30. public static void main(String[] args) throws IOException {
    31. try (AutoClose autoClose = new AutoClose()){
    32. autoClose.work();
    33. }
    34. }
    35. // 输出:
    36. work
    37. close
    38. Exception in thread "main" java.io.IOException: exception in work
    39. at org.example.common.Main$AutoClose.work(Main.java:21)
    40. at org.example.common.Main.main(Main.java:40)
    41. Suppressed: java.lang.RuntimeException: exception in close
    42. at org.example.common.Main$AutoClose.close(Main.java:27)
    43. at org.example.common.Main.main(Main.java:41)