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