1

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

2 回答 2

3

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

无论try语句是正常完成还是突然完成,它都会被关闭

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

于 2014-12-19T07:29:47.740 回答
3

是的,但不是在 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。

于 2014-12-19T07:30:06.860 回答