如果发生异常,try-with-resources会关闭资源吗?

时间:2014-12-19 07:25:58

标签: java try-with-resources

如果发生异常,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();
    }
}

2 个答案:

答案 0 :(得分:3)

即使它会抛出异常,它也会被关闭。

  

无论try语句是否完成,它都将被关闭   通常或突然

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

答案 1 :(得分:2)

是的,但不是在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契约而不是因为尝试使用资源。