简体   繁体   中英

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM