...
Code Block | ||
---|---|---|
| ||
Statement stmt = null; ResultSet rs = null; Connection conn = getConnection(); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sqlQuery); processResults(rs); } catch (SQLException e) { // forward to handler } finally { try { if (rs != null) { try { rs.close(); } catch (SQLException e) { } finally { // forward to handler } tryfinally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { // forward to handler } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { // forward to handler } } } } } } |
Compliant Solution (Java 1.7, try-with-resources)
...
Code Block | ||
---|---|---|
| ||
try (Connection conn = getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sqlQuery)) { processResults(rs); } catch (SQLException e) { // forward to handler } |
The try-with-resource construct will send any SQLException
to the catch clause, where it gets forwarded to an exception handler. This includes exceptions generated during the allocation of resources (that is, the creation of the Connection
, Statement
, or ResultSet
. It also includes any SQLException
thrown by processResults()
. Finally, it includes any SQLException
generated by closing rs
, stmt
, or conn
.
Noncompliant Code Example (File Handle)
...
Code Block | ||
---|---|---|
| ||
FileInputStream stream = null; BufferedReader bufRead = null; String line; try { stream = new FileInputStream(fileName); bufRead = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = bufRead.readLine()) != null) { sendLine(line); } } catch (IOException e) { // forward to handler } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // forward to handler } } } |
Compliant Solution (Java 1.7, try-with-resources)
...
Code Block | ||
---|---|---|
| ||
try (FileInputStream stream = new FileInputStream(fileName); BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream))) { String line; while ((line = bufRead.readLine()) != null) { sendLine(line); } } catch (IOException e) { // forward to handler } |
The try-with-resource construct will send any IOException
to the catch clause, where it gets forwarded to an exception handler. This includes exceptions generated during the allocation of resources (that is, the creation of the FileInputStream
or BufferedReader
. It also includes any IOException
thrown during the while loop. Finally, it includes any IOException
generated by closing bufRead
or stream
.
Risk Assessment
Failure to explicitly release non-memory system resources when they are no longer needed can result in resource exhaustion.
...