Try-with-resources and return statements in java(java中的try-with-resources和return语句)
问题描述
我想知道在 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.
如果由于 return 语句而从未到达语句末尾会发生什么?
What happens if the end of the statement is never reached because of a return statement?
推荐答案
基于Oracle的教程, "[资源] 将被关闭,无论 try 语句是正常完成还是突然完成".它将 abruptly
定义为来自异常.
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.
在 try
中返回是突然完成的一个例子,如 JLS 14.1.
Returning inside the try
is an example of abrupt completion, as defined by JLS 14.1.
这篇关于java中的try-with-resources和return语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java中的try-with-resources和return语句
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01