【问题标题】:Will try-with-resources close resources if exception happens?如果发生异常,try-with-resources 会关闭资源吗?
【发布时间】:2014-12-19 07:25:57
【问题描述】:

如果发生异常,try-with-resources 会关闭所有打开的资源吗?

private void insertUserInAccessTable(int user_id) throws SQLException {
    final String sql = "bla bla";   
    try( Connection con = ...; PreparedStatement ps = ... ) {
        ...
        if(i==0) throw new SQLException();
    }
}

【问题讨论】:

  • 这就是 try-with-resources 的全部意义所在。

标签: java try-with-resources


【解决方案1】:

是的,但不是在 try 块之外或在其主体内(在资源声明之后)初始化的那些。

// This connection is initialized beforehand and will not be
// closed automatically by try-with-resources
Connection conn = // ...

// The statement WILL always be closed, exception or not, before exiting the try block
try (Statement stmt = conn.createStatement())
{
    // This result set will NOT be closed (directly) by try-with-resources
    ResultSet rs = stmt.executeQuery(/*...*/);
}

* 当 try-with-resources 关闭 Statement 时,JDBC 说语句应该关闭它创建的 ResultSet。所以它可能会被关闭,但这只是因为 JDBC 合同而不是因为 try-with-resources。

【讨论】:

  • Oracles 教程显示 ResultSet 在 try 块体中出现,它也会被关闭,因为语句会,不是吗?
  • @Andy 这是 JDBC 功能,只有在您的 JDBC 驱动程序按照规范正确实现时才有效。它通常不适用于所有可关闭的对象。 try-with-resources 将关闭的唯一内容是 try 块的资源声明中列出的那些项目。
【解决方案2】:

即使抛出异常也会关闭。

无论try语句是否完成都会关闭 正常或突然

参考: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

【讨论】:

    猜你喜欢
    • 2020-01-01
    • 2016-09-29
    • 2011-10-16
    • 2015-08-13
    • 2013-09-12
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多