Exception when closing try-with-resources


public class Main {
    public static void main(String... args) throws Exception {
        try (Closable1 c1 = new Closable1(); Closable2 c2 = new Closable2()) {
            // none
        }
    }

    static class Closable1 implements AutoCloseable {
        @Override
        public void close() throws Exception {
            System.out.println("1 close.");
            throw new Exception("1 failed");
        }
    }

    static class Closable2 implements AutoCloseable {
        @Override
        public void close() throws Exception {
            System.out.println("2 close.");
            throw new Exception("2 failed");
        }
    }
}

std-in

2 close.
1 close.

std-error

Exception in thread "main" java.lang.Exception: 2 failed
	at com.company.Main$Closable2.close(Main.java:23)
	at com.company.Main.main(Main.java:8)
	Suppressed: java.lang.Exception: 1 failed
		at com.company.Main$Closable1.close(Main.java:15)
		at com.company.Main.main(Main.java:6)

Recommended Posts

Exception when closing try-with-resources
exception
Unexpected exception when using Java DateTimeFormatter
Java Exception StackTrace is determined when new