2017-07-18 52 views
0

有了這個代碼:Sonarlint多個關閉

Connection connection = null; 
PreparedStatement req = null; 
try { 
    connection = DriverManager.getConnection(url, user, password); 
    req = connection.prepareStatement(SQL); 
} finally { 
    if (connection != null) { 
     connection.close(); 
    } 
    if (req != null) { 
     req.close(); 
    } 
} 

SonarLint說:

關閉這個 「PreparedStatement的」 在第5行(req = ...

了 「終於」 條款,當我先關閉req

在「終於」條款關閉此「連接」上線4(connection = ...

我怎樣才能讓SonarLint幸福嗎?

回答

2

假設您使用的是java.sql.Connection,那麼您的代碼仍然可能以執行結束時未關閉的資源結束。

如果你從Java 6 javadocConnection.close()方法簽名,你會看到,它可以拋出一個SQLException。因此,由於您已經在finally區塊中,並且如果在關閉時發生異常,您的代碼將在不關閉請求的情況下退出該方法。

現在,如果您反轉關閉順序並從請求開始,則會發生同樣的情況。調用close()可能會失敗,那麼連接永遠不會關閉,從finally塊中直接跳轉到方法外。

爲了正確地關閉這兩個資源,我將建議對付這樣的:

Connection connection = null; 
try { 
    connection = DriverManager.getConnection(url, user, password); 
    PreparedStatement req = null; 
    try { 
    req = connection.prepareStatement(sql); 
    } finally { 
    if (req != null) { 
     req.close(); 
    } 
    } 
} finally { 
    if (connection != null) { 
    connection.close(); 
    } 

}