Search code examples
javatry-with-resources

Java Try With Resources - Order of Closing Resources


On running the below code

class MyResource1 implements AutoCloseable {
    public void close() throws IOException {
        System.out.print("1 ");
    }
}

class MyResource2 implements Closeable {
    public void close() throws IOException {
        throw new IOException();
    }
}

public class MapAndFlatMap {
    public static void main(String[] args) {
        try (
                MyResource1 r1 = new MyResource1();
                MyResource2 r2 = new MyResource2();
            ) {
            System.out.print("T ");
        } catch (IOException ioe) {
            System.out.print("IOE ");
        } finally {
            System.out.print("F ");
        }
    }
}

I am getting the below output

T IOE 1 F 

But I was expecting

T 1 IOE F

Even after changing the order of resources in try like the following

MyResource2 r2 = new MyResource2();
    MyResource1 r1 = new MyResource1();

There is no change in output .In my understanding the resources will be closed in opposite direction of their declaration . Is it correct ?


Solution

  • It is a documented behavior: "close methods of resources are called in the opposite order of their creation"