Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The problem of resource pool exhaustion is aggravated in the case of database connections. Traditionally, database servers allow have allowed a fixed number of connections, depending on configuration and licensing. Failing to release database connections can result in rapid exhaustion of available connections. This noncompliant code example does not close the connection if an error occurs while executing the statement or while processing the results.

...

Code Block
bgColor#FFcccc
Statement stmt = null;
ResultSet rs = null
Connection conn = getConnection(0);
try {
  stmt = conn.createStatement();
  rs = stmt.executeQuery(sqlQuery);
  processResults(rs);
} catch(SQLException e) { 
  // forward to handler  
} finally {
  rs.close();
  stmt.close();
}

Noncompliant Code Example

Again, while being still better, this code snippet is still noncompliant. This is because In this noncompliant code example, rs.close() might itself result in a SQLException, and so stmt.close() will never be called.

...

This compliant solution releases all acquired resources, regardless of any exceptions that might occur. Even though dereferencing bufRead might result in an exception, if a FileInputStream object is instantiated, it will be closed as required.

...