2014-12-19 80 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