try(Connection con = getConnection()) { try (PreparedStatement prep = con.prepareConnection("Update ...")) { //prep.doSomething(); //... //etc con.commit(); } catch (SQLException e) { //any other actions necessary on failure con.rollback(); //consider a re-throw, throwing a wrapping exception, etc }}
根据oracle文档,您可以将try-
with-resources块与常规try块结合使用。IMO,以上示例捕获了正确的逻辑,即:
- 如果没有问题,请尝试关闭PreparedStatement
- 如果内部块出了问题,(无论是什么)回滚当前事务
- 无论如何尝试关闭连接
- 如果关闭连接时出现问题,则无法回滚事务(因为这是连接上的一种方法,现在处于不确定状态),因此请勿尝试
在Java 6及更早版本中,我将使用三重嵌套的try块集(外部try-finally,中间try-catch,内部try-
finally)来完成此 *** 作。ARM语法确实使这个麻烦。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)