Continue loop iteration after exception is thrown

99封情书 提交于 2019-12-06 20:02:28

问题


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 ?


回答1:


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);
    }
}



回答2:


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;
    }
}


来源:https://stackoverflow.com/questions/16818532/continue-loop-iteration-after-exception-is-thrown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!