Reputation: 25
With this code :
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 says :
Close this "PreparedStatement" in a "finally" clause on line 5 (
req = ...
)
And when i close req
first :
Close this "Connection" in a "finally" clause on line 4 (
connection = ...
)
How can I make SonarLint happy ?
Upvotes: 1
Views: 341
Reputation: 3121
Assuming you are using java.sql.Connection
, your code can still end up with resources not being closed at the end of the execution.
If you look at the Connection.close()
method signature from Java 6 javadoc, you will see that it can throw a SQLException
. Consequently, as you are already in the finally
block and if an exception occurs while closing, your code will exit the method without closing the request.
Now, if you invert the close order and start with the request, the same thing can happen. Calling close()
can fail, then the connection is never closed, as from the finally block you jump once again directly outside the method.
In order to close both resources properly, I would recommend to deal with it like this:
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();
}
}
Upvotes: 3