Search code examples
c#recursionmodel-view-controllerstack-overflow

System.StackOverflowException C#


How can I bypass a stackoverflow exception or is there a better way to do this? Any help is greatly appreciated!

public MetricItemDetail GetData(int itemId, int itemTwoId)
{

        //some of my code goes here..

         try
                {
                    return new Class
                    {
                        Value = GetItemDetails(itemId, itemIdTwo)

                    };
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} Exception caught.", e);
                    return new Class();
                }

}

public double GetItemDetails(int itemId, int itemTwoId)
{

   var currentValue = GetData(itemId, itemTwoId); // The problem is here..this is where I get the stackoverflow exception

}

Solution

  • GetItemDetails and GetData methods are mutually called, it causes the "infinite" loop with stack allocations for each call, unfortunatelly stack size isn't infinite ;)

    See more details here: https://www.dotnetperls.com/stackoverflowexception

    StackOverflowException can't be bypased, it can't be catched, it must be avoided. It exists to protect .NET runtime from fatal crash.