2014-12-19 82 views
1

如果发生异常,请尝试使用资源关闭所有打开的资源?如果发生异常,请尝试使用资源关闭资源?

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

这就是试用资源的重点。 – 2014-12-19 07:35:23

回答

2

是的,但不是那些它的身体(在资源申报之后)。

// 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(/*...*/); 
} 

*当试穿与资源关闭Statement,JDBC说,声明应该关闭它创建的ResultSet。所以它可能会被封闭,但只是因为JDBC合同而不是因为试用资源。

+0

Oracles教程显示ResultSet在try块体内进入生命,它也将被关闭,因为语句将会,不会? – andy007 2014-12-19 07:38:03

+2

@Andy这是一个JDBC功能,只有当您的JDBC驱动程序按规范正确实现时才有效。一般来说,它并不适用于所有可关闭的对象。 try-with-resources将关闭的唯一东西是try块的资源声明中列出的项目。 – 2014-12-19 07:41:17