Share via


SYSK 78: Avoiding Infinite Loops Due to Error Handling Retries

Ok, so you want to do error handling, not just error logging…  So, you catch exception, examine it’s type and contents and try to resolve the problem…  Then what?  Then you want to retry the logic that failed before.  So, in many cases, you call yourself recursively and hope this time it will not throw an exception.  But what if it fails again, which will execute your handling logic and retry, just to fail again and again?  You get the picture.  You could have a class member variable which counts the number of retries…  Or, you could do something like this:

public void AvoidInfiniteLoop()

{

    try

    {

        // Some exception

        int x = 5, y = 0;

      int z = x / y;

    }

    catch (Exception ex)

    {

        // Assume we've done some handling here and now want to re-try

        // But we want to make sure we don't get in the infinite loop and end up with

        // 'out-of-stack' exception

        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(false);

        System.Diagnostics.StackFrame sf1 = st.GetFrame(0);

        System.Diagnostics.StackFrame sf2 = st.GetFrame(1);

        if (sf1.GetMethod().Equals(sf2.GetMethod()) == false)

        {

            // Retry

            AvoidInfiniteLoop();

        }

        else

        {

            MessageBox.Show("Error handling code did not resolve the problem");

        }

    }

}

 

Of course, this is not a panacea, but it does work for those cases where you want to recursively retry executing the method, and only one time…