提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
创建可以与try-with-resources技术一起使用的资源
public class Main { /* from 时代Java */ public static void main(String[] args) { try (FirstAutoCloseableResource resource1 = new FirstAutoCloseableResource(); SecondAutoCloseableResource resource2 = new SecondAutoCloseableResource()) { resource1.manipulateResource(); resource2.manipulateResource(); } catch (Exception e) { e.printStackTrace(); for (Throwable throwable : e.getSuppressed()) { System.out.println(throwable); } } } } class SecondAutoCloseableResource implements AutoCloseable { @Override public void close() throws Exception { /** 来自 N o w J a v a . c o m - 时 代 Java**/ // Close the resource as appropriate System.out.println("SecondAutoCloseableResource close method executed"); throw new UnsupportedOperationException( "A problem has occurred in SecondAutoCloseableResource"); } public void manipulateResource() { // Perform some resource specific operation System.out.println("SecondAutoCloseableResource manipulateResource method executed"); } } class FirstAutoCloseableResource implements AutoCloseable { @Override public void close() throws Exception { // Close the resource as appropriate System.out.println("FirstAutoCloseableResource close method executed"); throw new