Maximum stack depth reached: 1001

Let's understand what causes this error and how can we avoid it following the best practices.

Maximum stack depth reached: 1001

When you get to see this error, stop everything and check for only one thing.

Somewhere within your code you might be instantiating the class with in which you are. Am not saying this is the only reason for the error, but mostly it's because of this reason.

public class AccountsController(){
	
	//few variables 
	
	public void he{set; get;}
	public void she{set; get;}
  	public void me{set; get;}
  	public void it{set; get;}

	//this blows up everything!
	AccountsController ac = new AccountsController();
	
	public class foobar(){
	
	}
}

When a Visualforce page is loaded ..

The controller that’s associated to that page is also initialised.

Then all the variables are initialised.

Not only the variables but members of the class are also initialised.

Now, here is a member called ac which is nothing but the instantiation of the class in which it exists which is AccountsContoller.

It tries to instantiate the same class and again variables gets initialised, followed by members and again the class gets initialised.

This goes on and on until the maximum stack depth is reached.

All you need to do is, find if there is any self-instantiation that’s going on and try to remove it and you are good to go.

Other frequently encountered errors

Interested in learning LWC Development with me? Subscribe to my course (use this if you are out of India).