Connection (这可能引发异常)Statement (也可能引发异常)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街区是我关闭物品的地方。正如你所看到的,这是非常混乱的。我的问题是:这是清理这些资源的正确方法吗?
发布于 2014-12-01 20:44:23
在Java1.7之前,您的代码是捕获可关闭资源的异常的正确方法,只是您应该捕获SQLException而不是Exception。
从Java1.7开始,您可以使用the "try-with-resources" statement,它允许您声明资源,这些资源将在close()块完成时自动调用,从而保存样板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!发布于 2014-12-01 20:44:02
如果可以(至少需要Java 7) http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html,请使用参考资料查看一下
发布于 2014-12-01 20:50:42
是的,但是您可以通过编写可重用的代码(最好是在实用程序类中)来使它看起来更好看。
public static void close(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
// log exception
}
}
}并在最终块中使用此方法。为Connection和ResultSet添加类似的方法
https://stackoverflow.com/questions/27236853
复制相似问题