1

AccountTrigger

trigger AccountTrigger on Account (after insert)  { 
 try{
     if(Trigger.isAfter){
        AccountHandler.processAfterTrigger();
     }
 }
 catch(exception e) {
    System.debug('in exception');
 }
}

AccountHandler:

public class AccountHandler{
    public static void processAfterTrigger() {
          // DML 1 here
          // DML 2 here
          // DML 3 here  ------> This throws an exception ( Statement is not in inner try/catch )
       try{ 
          //DML 4 here 
       }catch(exception e) {
          System.debug('in inner exception');
       }
    }
}

As I understand the concept of try/catch. It says if you have handled the exception by yourself in apex, then there will be no auto Rollback unless we provide Savepoint & Rollback to it.

So, In the above case. What would happen if my DML 3 throws an exception? will DML 1 and 2 will rollback? Or as I have a try/catch block on the trigger. This will just catch the exception and no rollback scenario will be there?

Thanks in advance!

2 Answers 2

5

Try/catch (and finally) can be used at any level in your code flow. You could have no exception handling for 4 levels of method calls but as long as you have the level above surround the call down with try/catch, the exception handler will be invoked. Basically the depth of call stack is irrelevant within the try block.

Note, however, that there are two types of exception involved here:

  1. Catchable exceptions, like DmlException or custom exceptions. You can catch and process these (NB: you can always throw a new exception, or re-throw the exception in a catch block).
  2. Uncatchable exceptions, like those thrown when your app exceeds governor limits. There is nothing you can do to handle these except write your code to avoid them being thrown in the first place.

I wanted to also point out that the try/catch and System.debug behaviour you have shown in your question is an anti-pattern (users may think all is fine but actually that is not the case) and you should avoid it at pretty much any cost in production code.

4

No, it won't rollback because there's a catch exception on the call to the trigger handler.

The automated rollback only happens if you don't catch the exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.