使用此代码:
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说:
在第5行(PreparedStatement)中的"finally“子句中关闭这个”
req = ...“
当我先关闭req时:
在第4行(
connection = ...)中的"finally“子句中关闭这个”连接“
我怎样才能让SonarLint开心呢?
发布于 2017-07-18 15:24:01
假设您使用的是java.sql.Connection,那么您的代码仍然可以在执行结束时关闭资源。
如果您查看来自Connection.close()的Java 6 javadoc方法签名,您将看到它可以抛出一个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();
}
}https://stackoverflow.com/questions/45169405
复制相似问题