Closing resources that may throw exceptions
exception, java
Solution
Your code is the proper way of catching exceptions for closeable resources, prior to Java 1.7, except that you should catch `SQLException` instead of `Exception`.
Starting in Java 1.7, you can use the "try-with-resources" statement, which allows you to declare resources that will have `close()` called automatically when the `try` block finishes, saving boilerplate `finally` code.
try (Connection conn = Database.getConnection(); Statement st = conn.createStatement();
ResultSet set = st.executeQuery("SELECT * FROM THING")) {
// Your "try" code as before
}
catch (SQLException e) {
// Handle as before
}
// No "finally" to clean up resources needed!
Problem
- Get a `Connection` from the pool (this may throw an exception) - Create a `Statement` out of the connection (also may throw an exception) - Execute an SQL query using that statement and store it in a `ResultSet` (can throw as well) - Do stuff with the query results - Close `ResultSet` (exception!) - Close `Statement` (exception!) - Close `Connection` (exception!) Look at this code: ``` Connection conn = null; Statement st = null; ResultSet set = null; try { conn = Database.getConnection(); st = conn.createStatement(); set = st.executeQuery("SELECT * FROM THING"); // <-- Do stuff } catch (Exception e) { } finally { // Close set if possible if (set != null) { try { set.close(); } catch (Exception e) { } } // Close statement if possible if (st != null) { try { st.close(); } catch (Exception e) { } } // Close connection if possible if (conn != null) { try { conn.close(); } catch (Exception e) { } } } ``` The `finally` block is where I close my stuff. As you can see, it is very messy. My question would be: is this the right way to clean up those resources?