Skip to content

Instantly share code, notes, and snippets.

@varrix
Created September 20, 2017 02:16
Show Gist options
  • Save varrix/b28c9131ecd3fc74fc5f6ab608d53607 to your computer and use it in GitHub Desktop.
Save varrix/b28c9131ecd3fc74fc5f6ab608d53607 to your computer and use it in GitHub Desktop.
Source: https://stackoverflow.com/a/9260565 (see comments for rationale on particular counter-points one might have against this approach).
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
   }
}

According to the oracle documentation, you can combine a try-with-resources block with a regular try block. IMO, the above example captures the correct logic, which is:

  • Attempt to close the PreparedStatement if nothing goes wrong
  • If something goes wrong in the inner block, (no matter what is is) roll back the current transaction
  • Attempt to close the connection no matter what
  • If something goes wrong closing the connection, you can't rollback the transaction (as that's a method on the connection, which is now in indeterminate state), so don't try

In java 6 and earlier, I would do this with a triply nested set of try blocks (outer try-finally, middle try-catch, inner try-finally). ARM syntax does make this terser.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment