首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中尝试使用-语句

问在Java中尝试使用-语句
EN

Stack Overflow用户
提问于 2014-05-16 18:11:52
回答 1查看 470关注 0票数 3

在这个Java程序示例中:

代码语言:javascript
复制
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...
    }
}

当在静态方法示例()的正文中抛出OutOfMemoryError错误时,连接"con“和语句"stmt”是否在终止静态方法示例()之前自动关闭,尽管没有捕获这些错误的“捕捉”,所以main()中的其余代码确定这两个对象是关闭的?

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-16 18:19:19

是的;试探性资源结构总是关闭资源,即使它是不可检查的可抛出的(如OutOfMemoryError)。

这是在JLS 14.20.3中指定的,它以一个非常通用的语句开头,该语句表示资源是“自动关闭的”,但随后进入了资源关闭的各种例子。基本上,任何非null资源都总是关闭的,就好像close在为该资源创建的try-finally的finally子句中一样。即使try中有多个资源,情况也是如此(“关闭一个资源的异常并不会阻止其他资源的关闭”)。

演示它的简单类:

代码语言:javascript
复制
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();
    }
  }
}

输出:

代码语言:javascript
复制
closing second
closing first
Exception in thread "main" java.lang.OutOfMemoryError
    at Twr.main(Twr.java:19)

请注意,它们是按相反顺序关闭的;“第二”在“第一”之前关闭。在您的示例中,这意味着Statement在Connection之前关闭,这正是您想要的。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23702000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档