在这个Java程序示例中:
package test;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
public class Test
{
private static void example(){
String url = "jdbc:oracle:thin:@//localhost:7856/xe";
String user = "user";
String password = "pass";
try(Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement()){
throw new OutOfMemoryError("Error");
}catch (SQLException e){
System.err.println("SQLException");
}
}
public static void main(String [] args){
try{
example();
}catch (OutOfMemoryError e){
System.err.println("OutOfMemoryError");
}
// Rest of code here...
}
}
当在静态方法example()的主体中抛出OutOfMemoryError错误时,在终止静态方法example()之前,Connection“con”和Statement“stmt”会自动关闭,尽管没有任何捕获这些的“catch”错误,所以在main()的其余代码中确保这两个对象是关闭的?
谢谢.
解决方法:
是; try-with-resources构造总是关闭资源,即使它是一个未经检查的throwable(如OutOfMemoryError).
这在JLS 14.20.3中指定,它以一个非常通用的语句开始,即资源“自动关闭”,但随后会进入资源关闭时的各种示例.基本上,任何非空资源总是被关闭,就好像close已经在为一个资源创建的try-finally的finally子句中.即使在try中有多个资源,也就是这种情况(例如,“关闭一个资源时的异常不会阻止关闭其他资源”).
简单的类来演示它:
public class Twr {
private static class TwrCloseable implements AutoCloseable {
private final String id;
TwrCloseable(String id) {
this.id = id;
}
@Override
public void close() {
System.out.println("closing " + id);
}
}
public static void main(String[] args) {
try (TwrCloseable closeable1 = new TwrCloseable("first");
TwrCloseable closeable2 = new TwrCloseable("second")) {
throw new OutOfMemoryError();
}
}
}
输出:
closing second
closing first
Exception in thread "main" java.lang.OutOfMemoryError
at Twr.main(Twr.java:19)
请注意,它们以相反的顺序关闭; “第二个”在“第一个”之前关闭.在您的示例中,这意味着Statement在Connection之前关闭,这正是您想要的.
标签:java,try-with-resources 来源: https://codeday.me/bug/20190830/1770761.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。