SonarLint показывает следующие ошибки:
- 'Использовать try-with-resources или закрыть это "Statement" в предложении "finally".'
- 'Использовать try-with-ресурсы или закройте это «Соединение» в предложении «finally». Ошибки блокировщика
, даже если мы закрыли оператор Statement stmt, Соединение con в блоке finally.
Пожалуйста, найдите пример кода.
public String getProductNumber() throws BusinessDelegateException {
String productNo = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String query = //some query
try {
DataSource ds = getDataSource();
con = ds.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
productNo =.......
....................
}catch (Exception e) {
String errorMsg = "Error occured in getProductNumber()";
throw new BusinessDelegateException(errorMsg, e);
}finally{
try {
if(rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return productNo;
}
Мы смогли решить эту проблему, изменив блок finally следующим образом.Но все равно похоже на повторение блоков улова.Есть ли другой способ исправить это?
finally{
try {
if(rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stmt != null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}