Created
March 17, 2016 17:05
-
-
Save jehugaleahsa/d533b4c009e6e16044d2 to your computer and use it in GitHub Desktop.
Try/Catch/Finally Hell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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