Issue
Eclipse IDE always shows following warning:
Resource leak: 'rset' is not closed at this location
But for me the code seems to be correct:
Statement stmt = null;
ResultSet rset = null;
try {
stmt = connection.createStatement();
try {
String query = foo();
rset = stmt.executeQuery(query);
} catch (Exception e) {
String query = bar();
rset = stmt.executeQuery(query);
}
return JsonHandler.resultSetToJson(rset);
} finally {
if (rset != null)
rset.close();
if (stmt != null)
stmt.close();
}
How do I close the ResultSet?
Solution
As commented, your second assignment of rset
would let the first ResultSet
object become a candidate for garbage collection without being closed. Thus the warning from the compiler or your IDE.
To more reliably and clearly close your resources, use try-with-resources.
try-with-resources syntax
Modern Java offers the try-with-resources syntax feature to automatically close any object that implements AutoCloseable
with its single method close
. The resources will be closed in the reverse of the order in which they were instantiated. And they are closed whether your code completes successfully or throws an exception.
See The Java Tutorials provided free of cost by Oracle Corp.
Try-with-resources is one of my favorite features in Java. Along with text blocks, database work is much easier now, and more fool-proof.
Connnection
, Statement
, and ResultSet
are all such auto-closeable resources. So wrap them in try-with-resource syntax.
Exceptions
Get specific with your exceptions. Trap for the ones expected within the local context.
Code
Here is some untested code.
Notice how we name each ResultSet
object differently.
Notice how the nesting of try-with-resources calls communicates visually the cascading structure of our logic.
try
(
Connection conn = myDataSource.getConnection() ;
Statement stmt = conn.createStatement() ;
)
{
try
(
ResultSet rsetFoo = stmt.executeQuery( foo() );
)
{
return JsonHandler.resultSetToJson( rsetFoo );
}
catch ( SQLException | SQLTimeoutException e)
{
try
(
ResultSet rsetBar = stmt.executeQuery( bar() );
)
{
return JsonHandler.resultSetToJson( rsetBar );
}
}
}
catch ( SQLException e )
{
…
}
catch ( SQLTimeoutException e )
{
…
}
If you had searched before posting, you would have found many existing examples, and much discussion, already posted on Stack Overflow.
Answered By - Basil Bourque
Answer Checked By - Clifford M. (JavaFixing Volunteer)