...
In the case above, if an error occurs while executing the statement, or while processing the results of the statement, the connection is not closed. The use of a finally
block can be used to ensure that close statements are eventually called.
Noncompliant Code Example
However, while being slightly better, this code is also non-compliant. Both rs
and stmt
might be null.
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null Connection conn = getConnection(0; try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch(SQLException e) { } finally { rs.close(); stmt.close(); } } |
Noncompliant Code Example
AgainHowever, while being slightly still better, this the code is also still non-compliant. Both rs
and stmt
might be nullThis is because rs.close()
might itself result in a SQLException
, and so stmt.close()
will never be called.
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch(SQLException e) { } finally { if(rs != null) { rs.close(); } if(stmt != null) { stmt.close(); } } } |
...
Compliant Solution
This compliant solution shows how to ensure that resources have been released.
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch(SQLException e) { } finally { try { if(rs != null) { rs.close(); } } finally ( try { if(stmt != null) { stmt.close(); } } finally { conn.close(); } } } |
Noncompliant Code Example
The worst form of non-compliance is not calling methods to release the resource at all. If files are opened, they must be explicitly closed when their work is done.
...