4
votes

I know that unchecked Exceptions (RuntimeExceptions) will usually cause a rollack of your transaction but what happens if you catch that exception in the same mothod? I want the rollback the whole transaction when errorOccurred is true. But I wonder if catching Exception will swallow the RuntimeException hence causing the transaction to NOT rollback? Does this code still rollback the transaction?

public static void main(String[] args) {
   try {
      // boring stuff...
      if(errorOccurred)
         throw new RuntimeException("RuntimeException is thrown.");
   } catch (Exception e) {
      System.out.println("RuntimeException cought. Does is still rollback transaction?");
   }
}
1
If you pass to manual exception handling you should rollback yourself. - NiVeR
why do you want to catch the exception then? - Jack Flamp
@JackFlamp there are some other things going on inside this method which requires to handle the checked exception as well. Otherwise I would get rid of that. - gozluklu_marti
then you should handle those exceptions individually. RuntimeExceptions are defined to cause a rollback - Jack Flamp
@JackFlamp What I wanted to know is that if the rollback kicks in as soon as a RuntimeException is thrown or does it wait untill the catch/finally blocks to run first? - gozluklu_marti

1 Answers

2
votes

If your program catches the run time exception that means exception has not reached to JEE container, hence from JEE container perspective it is normal program execution, so it will not rollback transaction.

If you want to catch the runtime exception as well as rollback the transaction you need to programmatically rollback the transaction on those specific runtime exception. In session bean it provides sessioncontext object which has method setRollbackOnly , with this method you can inform the container to rollback transaction without throwing runtime exception. Message driven bean also provides messagedrivencontext object which can be used to rollack transaction[ check for MDB https://docs.oracle.com/javaee/6/tutorial/doc/bnbpo.html]