考虑代码:
PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.createStatement(myQueryString); rs = ps.executeQuery(); // process the results... } catch (java.sql.SQLException e) { log.error("an error!", e); throw new MyAppException("I'm sorry. Your query did not work."); } finally { ps.close(); rs.close(); }以上不编译,因为 PreparedStatement。 close()和 ResultSet.close()抛出 java.sql.SQLException 。那么我要在finally子句中添加try / catch块吗?或者将close语句移动到try子句中?或者只是不打扰调用close?
The above does not compile, because both PreparedStatement.close() and ResultSet.close() throw a java.sql.SQLException. So do I add a try/catch block to the finally clause? Or move the close statements into the try clause? Or just not bother calling close?
推荐答案对于文件I / O,我通常会在finally块中添加try / catch。但是,你必须小心不要抛出finally块中的任何异常,因为它们会导致原始异常(如果有的话)丢失。
For file I/O, I generally add a try/catch to the finally block. However, you must be careful not to throw any exceptions from the finally block, since they will cause the original exception (if any) to be lost.
参见本文有关数据库连接关闭的更具体示例。
See this article for a more specific example of database connection closing.
更多推荐
在哪里关闭java PreparedStatements和ResultSet?
发布评论