Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is proper code pattern to finalize transactions in Java (rollback on exception and commit on success)?
    text
    copied!<p>I'm looking for generic code pattern to properly handle transaction with respect to possible exception. I assume there is common code pattern for that, no matter what concrete kind of transaction we are dealing with.</p> <p>I have a method that executes something in transaction and want to rethrow Exception that may occur when inside transactional code block. Here is an example of such method:</p> <pre><code>protected void doIt() { // for JDBC connection transaction may be started automatically // but assume we start it here Tran tran = session.beginTran(); try { // here comes code that does some processing // modifies some data in transaction // etc. // success - so commit tran.commit(); } catch (Exception ex) { // many different exceptions may be thrown // subclass of RuntimeException, SQLException etc. // error - so rollback tran.rollback(); // now rethrow ex throw ex; // this line causes trouble, see description below } } </code></pre> <p>Now - there is compile error in method <code>doIt</code>. It must declare <code>throws Exception</code> but this is not acceptable because method <code>doIt</code> is used in many places and adding <code>throws Exception</code> leads to subsequent modifications in places of direct and indirect use of <code>doIt</code>. It's because of known Java Language design problem with declared exceptions.</p> <p>Now the <strong>question</strong>: how to change exception vs transaction handling code to achieve my goal - properly handle transaction finalization (perform commit or rollback based on success condition) and rethrow exactly the same exception that may be catched in transactional code block.</p> <p>I know that I could do something like <code>throw new RuntimeException(ex)</code> but this throws exception of other class and I want to avoid such solution.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload