Search code examples
c#try-catchcounter

catch consecutive error in .net c # using try catch


I have a block of code that is executed N times within a foreach loop, and I need to detect if an error occurs more than 5 times in a row. I set a counter but I don't know how to detect if the increase was continuous or intermittently. And I need to stop the process only when those errors are continuous.

The code.

        int consecutiveError = 0;
        try
        {
            foreach (var item in collection)
            {
                //......
                //fail
            }
        }
        catch (Exception ex)
        {
            if (consecutiveError == 5)
                stopProccess();
        }

Solution

  • Try the following code:

      int errorCount = 0;
      foreach ( var item in collection )
      {
        try
        {
          //Code ......
          //fail
    
          //At end of code
          errorCount = 0;
        }
        catch ( Exception ex )
        {
          errorCount++;
          if ( errorCount > 5 )
          {
            stopProccess();
            throw;
          }
        }
      }