- 从池中获取
Connection
(这可能会抛出异常) - 使用连接创建
Statement
(也可能会抛出异常) - 使用该语句执行SQL查询并将其存储在
ResultSet
中(也可能会抛出异常) - 对查询结果进行处理
- 关闭
ResultSet
(异常!) - 关闭
Statement
(异常!) - 关闭
Connection
(异常!)
看看这段代码:
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) {
}
}
}
finally
块是我关闭资源的地方。正如您所看到的,它非常凌乱。我的问题是:这是清理这些资源的正确方法吗?
Closer
可以在Java 6中模拟try-with-resource。http://wil.boayue.com/blog/2013/09/13/java-7-automatic-resource-management/ - 而无数的closeQuietly(Closable)
方法可以帮助你缩短代码片段(尽管只是半正确的,因为关闭资源时出现异常可能意味着写操作失败,因此不应被忽略)。 - zapl