C# 抛出异常后继续循环迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16818532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Continue loop iteration after exception is thrown
提问by Dimitar Tsonev
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 errorLoghas two entries (for i==2and i==4)
So, is it possible to continue the iteration even the exception is thrown ?
现在,很明显,执行将停止i==2,但我想让它完成整个迭代,以便在其中errorLog有两个条目(fori==2和i==4)那么,即使抛出异常,是否也可以继续迭代?
采纳答案by Servy
Just change the scope of the catchto be inside the loop, not outside it:
只需将 的范围更改为catch在循环内,而不是在循环外:
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);
}
}
回答by Kenneth
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;
}
}

