Java 中的 Try-with-resources 和 return 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22947755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Try-with-resources and return statements in java
提问by maff
I'm wondering if putting a returnstatement inside a try-with-resourcesblock prevents the resource to be automatically closed.
我想知道在try-with-resources块中放置return语句是否会阻止资源自动关闭。
try(Connection conn = ...) {
return conn.createStatement().execute("...");
}
If I write something like this will the Connectionbe closed? In the Oracle documentation it is stated that:
如果我写这样的东西,连接会被关闭吗?在 Oracle 文档中指出:
The try-with-resources statement ensures that each resource is closed at the end of the statement.
try-with-resources 语句确保每个资源在语句结束时关闭。
What happens if the end of the statement is never reached because of a return statement?
如果由于 return 语句而从未到达语句的末尾会发生什么?
采纳答案by merlin2011
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.
根据Oracle 的教程,“无论 try 语句是正常完成还是突然完成,[资源] 都将关闭”。它定义abruptly
为来自异常。
Returning inside the try
is an example of abrupt completion, as defined by JLS 14.1.
返回内部try
是JLS 14.1定义的一个突然完成的例子。
回答by Nurettin Armutcu
The resource will be closed automatically (even with a return
statement) since it implements the AutoCloseable
interface. Here is an example which outputs "closed successfully":
资源将自动关闭(即使使用return
语句),因为它实现了AutoCloseable
接口。这是一个输出“成功关闭”的示例:
public class Main {
public static void main(String[] args) {
try (Foobar foobar = new Foobar()) {
return;
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Foobar implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("closed successfully");
}
}