As others have pointed out, JDBC resources (statements, result sets, etc...) are rarely null
. If they are, you have bigger issues on your hands than NullPointerException
s. In that regard, the NullPointerException
s will help alert you to severe problems with your JDBC driver. The typical checking for null
before calling close()
would silently hide the problem if your JDBC driver was, in fact, providing you with null
references.
As well, not all JDBC drivers follow the specification precisely. For example, some drivers will not automatically close a ResultSet
when it's associated Statement
is closed. Therefore, you have to ensure that you explicitly close both the ResultSet
and its Statement
(sigh).
In practice, I have found this technique useful (although its not the prettiest):
PreparedStatement statement = connection.prepareStatement("...");
try {
ResultSet results = statement.executeQuery();
try {
while (results.next()) {
// ...
}
} finally {
results.close();
}
} finally {
statement.close();
}
This technique guarantees that every close()
statement is executed, starting with the ResultSet
and working its way outward. NullPointerException
s are still thrown should the driver provide you with null
references, but I allow this for the reasons explained at the beginning. SQLException
s are still thrown if any of the close()
statements fail (I consider this a good thing - I want to know if something is going wrong).