Dimitar Tsonev
Dimitar Tsonev

Reputation: 3882

Continue loop iteration after exception is thrown

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

Answers (2)

Kenneth
Kenneth

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

Servy
Servy

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

Related Questions