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.
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:
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
}
}
Now - there is compile error in method doIt
. It must declare throws Exception
but this is not acceptable because method doIt
is used in many places and adding throws Exception
leads to subsequent modifications in places of direct and indirect use of doIt
. It's because of known Java Language design problem with declared exceptions.
Now the question: 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.
I know that I could do something like throw new RuntimeException(ex)
but this throws exception of other class and I want to avoid such solution.