Skip to content

Instantly share code, notes, and snippets.

@jehugaleahsa
Created March 17, 2016 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jehugaleahsa/d533b4c009e6e16044d2 to your computer and use it in GitHub Desktop.
Save jehugaleahsa/d533b4c009e6e16044d2 to your computer and use it in GitHub Desktop.
Try/Catch/Finally Hell
List<String> requestCodes(String dbUrl, String id) {
List<String> result = new ArrayList<String>();
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(dbUrl);
stmt = conn.prepareStatement("SELECT * FROM customers WHERE id = ?");
stmt.setString(1, id);
rs = stmt.executeQuery();
while (rs.next()) {
result.add(rs.getString("code"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close(); // close() throws an exception...
} catch (SQLException e) {
e.printStackTrace(); // ...have to catch it to free 'stmt'
}
}
if (stmt != null) {
try {
stmt.close(); // again, close() throws an exception...
} catch (SQLException ignore) {
e.printStackTrace(); // ...have to catch it to free 'conn'
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
e.printStackTrace();
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment