What is the correct code template to complete transactions in Java (rollback by exception and committing success)?

I am looking for a generic code template for the correct processing of a transaction regarding a possible exception. I assume that for this there is a common code template, regardless of the specific type of transaction with which we are dealing.

I have a method that executes something in a transaction and wants to reconstruct an exception that can occur when inside a block of transactional code. Here is an example of such a method:

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
  }      
}

- doIt. throws Exception, , doIt , throws Exception doIt. - Java .

: - ( ) , .

, - throw new RuntimeException(ex), , .

+5
2

- .

protected void doIt() {
  // for JDBC connection transaction may be started automatically
  // but assume we start it here
  Tran tran = session.beginTran();
  bool success = false;
  try {
    // here comes code that does some processing
    // modifies some data in transaction
    // etc.

    // success - so commit
    tran.commit();
    success = true;
  } finally { 
     // error - so rollback
     if (! success)
       tran.rollback();
  }      
}

.. tran , (tran.isFinished()) - , bool. (, runtimeexception , ) , finally , .

, log-em - ( - ). - , , , .

+7

, Java 5+, Spring (@Transactional), .

, , :

import org.springframework.transaction.annotation.Transactional;

@Transactional(rollbackFor = Exception.class)
protected void doIt()

, : http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html. 9.5.6 - @Transactional.

+1