在java中尝试使用资源和返回语句 [英] Try-with-resources and return statements in java
问题描述
我想知道在 try-with-resources 块中放置 return 语句是否会阻止资源自动关闭。
I'm wondering if putting a return statement inside a try-with-resources block prevents the resource to be automatically closed.
try(Connection conn = ...) {
return conn.createStatement().execute("...");
}
如果我写这样的话, Connection 被关闭?在Oracle文档中,声明:
If I write something like this will the Connection be closed? In the Oracle documentation it is stated that:
try-with-resources语句确保在语句结束时关闭每个资源。
The try-with-resources statement ensures that each resource is closed at the end of the statement.
如果由于返回语句而从未到达语句的结尾会发生什么?
What happens if the end of the statement is never reached because of a return statement?
推荐答案
基于 Oracle的教程,[资源]将被关闭,无论try语句是正常完成还是突然完成。它从异常中定义突然
。
Based on Oracle's tutorial, "[the resource] will be closed regardless of whether the try statement completes normally or abruptly". It defines abruptly
as from an exception.
返回尝试
是突然完成的示例,由 JLS定义14.1 。
Returning inside the try
is an example of abrupt completion, as defined by JLS 14.1.
这篇关于在java中尝试使用资源和返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!