Hello friends, In this tutorial, I will provide a working example that helps you to avoid “Maximum trigger depth exceeded” or “Recursive Trigger” exception in salesforce.

After completing this tutorial, you’ll able to handle:

  • Maximum trigger depth exceeded exception.
  • Recursive trigger exception.

So, let’s start,

To resolve “Maximum trigger depth exceeded” or “Recursive Trigger” exception in trigger please follow the below steps,

Step1: Create a class with static boolean variable and set its value true to avoid the exception.

 public class RecursiveHandler{
     public static Boolean IsNotRecursive = true;
 }

Step2: Check the Boolean flag value before process your code condition and set the flag value to false at the beginning of your process. After setting flag value (Boolean variable) false, the recursion will stop and your code will process without any exception.

 trigger CreateContact on Contact (before insert) {
    List<Account> lstAcc=[SELECT Id FROM Account Order by Name limit 1];
    if(RecursiveHandler.IsNotRecursive){
        RecursiveHandler.IsNotRecursive = false;
        for(Contact c:trigger.New){
            Contact obj=new Contact();
            obj.AccountId=lstAcc[0].Id;
            obj.LastName='LastName';
            insert obj;
        }
    }
 }

I hope that above code will helps you to resolve the “Maximum trigger depth exceeded” or “Recursive Trigger” exception in salesforce.

See also:
Conclusion:
Hope you like this tutorial, for any question and suggestion please feel free to comment.
Thank you.