Versions Compared

Key

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

...

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

Noncompliant Code Example

...

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();
}

...

Code Block
bgColor#FFcccc
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 {
  if(rs != null) {
    rs.close();
  }
  if(stmt != null) {
    stmt.close();
  }
}

...

Code Block
bgColor#ccccff
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) {
      rs.close();
    }
  } finally {
    try {
      if(stmt != null) {
        stmt.close();
      }
    }
    finally {
      conn.close();
    }
  }
}

...

Code Block
bgColor#FFcccc
public int processFile(String fileName) throws IOException, FileNotFoundException {
  FileInputStream stream = new FileInputStream(fileName);
  BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream));
  String line;
  while((line = bufRead.readLine()) != null) {
    sendLine(line);
  }
  return 1;
}

Compliant

...

Solution

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

Code Block
bgColor#ccccff
FileInputStream stream = null;
BufferedReader bufRead = null;
String line;
try {
  stream = new FileInputStream(fileName);
  bufRead = new BufferedReader(new InputStreamReader(stream));
  while((line = bufRead.readLine()) != null) {
    sendLine(line);
  }
} catch (IOException e) { /* forward to handler */ }
finally {
  if(stream != null) { 
    stream.close();
  } 
}

...