抛出exception后继续循环迭代

假设我有一个这样的代码:

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

现在,显然执行将在i==2上停止,但我想让它完成整个迭代,以便在errorLog有两个条目(对于i==2i==4 )所以,是否可能继续迭代甚至抛出exception?

只需将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); } } 

为什么要抛出exception呢? 您可以立即写入日志:

 for (int i = 0; i < 10; i++) { if (i == 2 || i == 4) { errorLog.AppendLine(ex.Message); continue; } }