Java Try With Resources - 关闭资源的顺序
Java Try With Resources - Order of Closing Resources
在 运行 下面的代码
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();
输出没有变化。据我所知,资源将在声明的相反方向关闭。正确吗?
在 运行 下面的代码
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();
输出没有变化。据我所知,资源将在声明的相反方向关闭。正确吗?