Reputation: 3882
Let's say I have a code like this:
try
{
for (int i = 0; i < 10; i++)
{
if (i == 2 || i == 4)
{
throw new Exception("Test " + i);
}
}
}
catch (Exception ex)
{
errorLog.AppendLine(ex.Message);
}
Now, it's obvious that the execution will stop on i==2
, but I want to make it finish the whole iteration so that in the errorLog
has two entries (for i==2
and i==4
)
So, is it possible to continue the iteration even the exception is thrown ?
Upvotes: 24
Views: 56573
Reputation: 28737
Why do you throw the exception at all? You could just write to the log immediately:
for (int i = 0; i < 10; i++)
{
if (i == 2 || i == 4)
{
errorLog.AppendLine(ex.Message);
continue;
}
}
Upvotes: 8
Reputation: 203821
Just change the scope of the catch
to be inside the loop, not outside it:
for (int i = 0; i < 10; i++)
{
try
{
if (i == 2 || i == 4)
{
throw new Exception("Test " + i);
}
}
catch (Exception ex)
{
errorLog.AppendLine(ex.Message);
}
}
Upvotes: 68