gpt4 book ai didi

java - 继承和资源尝试

转载 作者:行者123 更新时间:2023-12-01 16:45:52 25 4
gpt4 key购买 nike

假设有两个类实现 AutoCloseable 接口(interface),如下所示:

public class Closing1 implements AutoCloseable {

private boolean closed;

@Override
public void close() throws Exception {
if (closed) {
throw new Exception("Closed Already");
}
this.closed = true;
System.out.println("Closing1 closed");
}

public boolean isClosed() {
return closed;
}

}

public class Closing2 implements AutoCloseable {

private Closing1 cl1;

public Closing2(Closing1 cl1) {
this.cl1 = cl1;
}

@Override
public void close() throws Exception {
if(!cl1.isClosed()) {
throw new Exception("Closing1 not closed");
}
System.out.println("Closing2 closed");
}

}

我发现尝试资源的所有变体都会导致异常!我在这里遗漏了什么吗,或者这只是 TWR 的设计方式?

        try(Closing1 c1 = new Closing1();Closing2 c2 = new Closing2(c1)){
System.out.println("Done");
} //Exception while auto closing C2

        try(Closing1 c1 = new Closing1();Closing2 c2 = new Closing2(c1)){
System.out.println("Done");
c1.close();
} // exception while auto closing c1

最佳答案

Try-with-resources 将以与声明相反的顺序关闭资源。这意味着将首先调用c2.close(),这将在您编写代码时抛出异常。

关于java - 继承和资源尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107847/

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