gpt4 book ai didi

Java Try With Resources - 关闭资源的顺序

转载 作者:行者123 更新时间:2023-11-29 08:29:29 28 4
gpt4 key购买 nike

运行下面的代码

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 ");
}
}
}

我得到以下输出

T IOE 1 F 

但我很期待

T 1 IOE F

即使在 try 中更改了资源的顺序,如下所示

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

输出没有变化。据我所知,资源将在声明的相反方向关闭。是否正确?

最佳答案

关于Java Try With Resources - 关闭资源的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49505074/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com