继续循环迭代异常被抛出后, [英] Continue loop iteration after exception is thrown
本文介绍了继续循环迭代异常被抛出后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有一个code是这样的:
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);
}
现在,很明显,该执行将停止我== 2
,但我希望把它完成整个迭代,以使错误日志
有两个条目(我== 2
和我== 4
)
那么,是不是可以继续循环,甚至抛出异常?
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 ?
推荐答案
只要改变抓
的范围是内循环,而不是在它之外:
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);
}
}
这篇关于继续循环迭代异常被抛出后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文