user358448
user358448

Reputation: 1187

How is exception handled in transactional context with finally block?

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

Upvotes: 4

Views: 4180

Answers (4)

EvenLisle
EvenLisle

Reputation: 4812

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
}

Upvotes: 1

dwalldorf
dwalldorf

Reputation: 1379

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.

Upvotes: 0

Jigar Parekh
Jigar Parekh

Reputation: 6283

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()

Upvotes: 0

subodh
subodh

Reputation: 6158

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.

Upvotes: 1

Related Questions