[英]SonarLint is still showing blocker errors even though we have handled the statement, Connection closes in finally block
SonarLint is showing below errors: SonarLint 显示以下错误:
Please find the sample code.请找到示例代码。
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;
}
We were able to fix the issue by modifying the finally block in below manner.我们能够通过以下方式修改 finally 块来解决问题。 But still it seems like repetition of catch blocks.
但它似乎仍然是 catch 块的重复。 Any other way we can fix this?
我们还有其他方法可以解决这个问题吗?
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();
}
}
Without try-with-resources you can only improve the code by using methods for re-usability, call main method: 没有try-with-resources,您只能通过使用方法来提高代码的可重用性,调用main方法:
closeResources(rs, stmt, con);
Which will call each for each resource a different method for example Statement: 它将为每种资源调用不同的方法,例如Statement:
public void closeResource(Statement stmt) {
if (stmt != null) {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
BTW, you better use logger instead of e.printStackTrace() 顺便说一句,您最好使用logger而不是e.printStackTrace()
For complete solution, you can check extensive example which add resources in array and close them in a loop: 要获得完整的解决方案,您可以查看广泛的示例 ,这些示例将资源添加到数组中并在循环中将其关闭:
for (Closeable resource : resources) { try { resource.close();
Use Try-with-resources.使用资源尝试。 This is the best option.
这是最好的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.