哪个更适合finally块:
finally { try { con.close(); stat.close(); } catch (SQLException sqlee) { sqlee.printStackTrace(); } }
要么:
finally { try { if (con != null) { con.close(); } if (stat != null) { stat.close(); } } catch (SQLException sqlee) { sqlee.printStackTrace(); } }
此外,如果您已经使用Java 7,则应考虑使用
try-with-resources
,它会自动关闭资源.从链接的教程:
The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
翻译自:https://stackoverflow.com/questions/18114905/close-connection-and-statement-finally