Closing Resources That May Throw Exceptions
- Get
Connection
from the pool (this might throw an exception) - Create
Statement
from connection (can also throw an exception) - Execute the SQL query using this statement and store it in
ResultSet
(can also quit) - Make stuff with 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 block finally
is where I close my stuff. As you can see, this is very messy. My question is, would this be the correct way to clean up these resources?
source to share
Your code is the proper way to catch exceptions for closedable resources prior to Java 1.7, except that you should catch SQLException
instead Exception
.
As of Java 1.7, you can use the try-with-resources statement , which allows you to declare resources to have close()
, called automatically when the block try
ends, keeping the template code finally
.
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!
source to share
Have a look at trying with resources if you can (requires at least Java 7) http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
source to share
Yes, but you can do it better by writing code (preferably in a utility class) that can be reused
public static void close(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
// log exception
}
}
}
and use this method in your finally block. Add similar methods for Connection
andResultSet
source to share