The blog has moved to the new site F10Debug.com

Friday, November 3, 2017

Continue loop iteration after exception is thrown

One of my friend working on one project which has task and task has for loop inside.

Like this,

try
{
    foreach (var item in collection)
    {
        if (item == null)
        {
            throw new Exception("item {0} is null" + item);
        }
    }
}
catch (Exception ex)
{
    WriteLog.AppendLine(ex.Message);
}

but loop was exited when any exception was occur, but what he want if any exception comes just leave that records, log the exception and countinue the loop.

Was what i suggested is "Use try and Catch block inside the loop", so that if any error comes while processing item, then it will log the exception and continue the loop.

foreach (var item in collection)
{
    try
      {
           if (item == null)
           {
              throw new Exception("item {0} is null" + item);
           }
      }
    catch (Exception ex)
      {
          WriteLog.AppendLine(ex.Message);
      }
}


No comments:

Post a Comment