Hello Everyone, In this tutorial, I will let you know why “Maximum Trigger Depth Exceeded” exception occurred in salesforce with an example.

After completing this tutorial, you’ll able to understand:
  • Why this “Maximum Trigger Depth Exceeded” exception occurred?
So let’s begin

According to salesforce governor limits, total stack depth for any apex invocation that recursively fires trigger due to DML (insert, update, or delete) statement size is 16. If you beyond this limit you will get “Maximum Trigger Depth Exceeded” exception.

For Example:
Create a trigger on Contact object with the following code:
 trigger CreateContact on Contact (before insert) {
    List<Account> lstAcc=[SELECT Id FROM Account Order by Name limit 1];
    for(Contact c:trigger.New){
        Contact obj=new Contact();
        obj.AccountId=lstAcc[0].Id;
        obj.LastName='LastName';
        insert obj;
    }
 }

After creating this trigger, click on the contact tab and create a new contact, when you hit the Save button after filling mandatory information in contact, you will run into the “Maximum Trigger Depth Exceeded” exception.



 
Reason for getting the error:
My Trigger concept is whenever contact record is created, the same record should be created as a duplicate record. After inserting a record the above trigger will fire then duplicate record will process after that trigger will call recursively, this causes a “Maximum Trigger Depth Exceeded” error.

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