Question

If i have transactional method like the one below, when is the finally block executed in case of transaction commit and rollback? For example if "persist some entity in database with hibernate" throws some hibernate exception which is true?

1) transaction rollback 2) finally block is executed

or

1) finally block is executed 2) transaction rollback

public void someTransactionalPersist(...) {
     try {
     // persist some entity in database with hibernate
     } finally {
        // do something 
     }
}
Was it helpful?

Solution 2

In both case finally block will executed finally. sequence will be, If your try block throw exception then it will rollback first and then finally block will executed.

OTHER TIPS

try{
    //This is executed if an exception is not thrown
} catch(Exception e){
    //This is executed if an exception is thrown
} finally{
    //This is executed regardless of which of the above was executed
}

assuming someTransactionalPersist method is start point of transaction then if there is any exception in try block then first finally will be executed and if there is runtime exception thrown from finally block then spring will do rollback as default configuration.

if you want rollback for perticular exception then you have to configure @Transactional with rollbackFor.

if you want to manually mark transaction as rollback without further throwing exception/runtime exception then you have to do this in catch block TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()

Regarding the specification http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2

If there is no Exception, after the try has executed without errors, the finally block will be executed. If there is an error in try and there is a catch-block, catching that exception, the catch block is executed. Afterwards, the finally block will be executed.

If there is an error in the try block and there is no catch block, catching that exception, the finally block will be executed and your method will throw that uncaught exception.

So, the finally block will always be executed and will always be the last block, being executed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top