资源是否在最终之前或之后关闭? [英] Are resources closed before or after the finally?
本文介绍了资源是否在最终之前或之后关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java 7的try-with-resources中,我不知道finally块和自动关闭发生了哪个顺序。订单是什么?
In Java 7's try-with-resources, I don't know which order the finally block and the auto-closing happens. What's the order?
BaseResource b = new BaseResource(); // not auto-closeable; must be stop'ed
try(AdvancedResource a = new AdvancedResource(b)) {
}
finally {
b.stop(); // will this happen before or after a.close()?
}
推荐答案
资源在捕获之前关闭或者最后是块。请参阅此教程。
The resource gets closed before catch or finally blocks. See this tutorial.
try-with-resources语句可以像普通的try语句一样有catch和finally块。在try-with-resources语句中,任何catch或finally块在声明的资源关闭后运行。
A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
评估这个是一个示例代码:
To evaluate this is a sample code:
class ClosableDummy implements Closeable {
public void close() {
System.out.println("closing");
}
}
public class ClosableDemo {
public static void main(String[] args) {
try (ClosableDummy closableDummy = new ClosableDummy()) {
System.out.println("try exit");
throw new Exception();
} catch (Exception ex) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
}
}
输出:
try exit
closing
catch
finally
这篇关于资源是否在最终之前或之后关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文