繁体   English   中英

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

[英]Will try-with-resources close resources if exception happens?

如果发生异常,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语句是正常完成还是突然完成,它将关闭

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM