How handle an exception in a loop and keep iterating in c#

By | November 4, 2017

How handle an exception in a loop and keep iterating in c#

One of my friend working on one project which has task and task has for loop inside. The for loop was getting break if any exception comes,

What he has written in task is like,

try
{
   foreach (var item in collection)
    {
       if (item == null)
       {
          throw new Exception("item {0} is null" + item);
       }
    }
}
catch (Exception ex)
{
    WriteLog.AppendLine(ex.Message);
}
And what he wants is “If any exception comes in loop, just leave that records, log the exception and countinue the loop.”

So what i suggested is “Use try and Catch block inside the loop”, so that if any error comes while processing the item, 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);
    }
}