你可以在 catch 块中使用一个名为 flag 的 bool 变量,并在 catch 块执行后,如果 flag 表示执行了 catch 块,则执行 continue 语句。
foreach (string l in lUserName)
{
bool isError = false;
try
{
newMessages = FetchUnseenMessages();
}
catch
{
isError = true;
}
if(isError) continue;
}
如果 continue 语句退出一个或多个带有关联 finally 块的 try 块,控制权最初将转移到最内层 try 语句的 finally 块。当控制权到达 finally 块的结束点时,控制权将转移到下一个封闭 try 语句的 finally 块。这个过程重复进行,直到所有介于 try 语句的 finally 块都被执行,
msdn。
根据给定的细节,continue 的行为应该是正常的,你不应该有任何问题。你可能有其他问题,比如
closure variable in a loop,你可以在
这里 阅读更多关于变量闭包的内容。
我已经进行了测试来验证给定的场景,看起来是正常的。
for (int i = 0; i < 3; i++)
{
try
{
Console.WriteLine("Outer loop start");
foreach (int l in new int[] {1,2,3})
{
Console.WriteLine("Inner loop start");
try
{
Console.WriteLine(l);
throw new Exception("e");
}
catch
{
Console.WriteLine("In inner catch about to continue");
continue;
}
Console.WriteLine("Inner loop ends after catch");
}
Console.WriteLine("Outer loop end");
}
catch
{
Console.WriteLine("In outer catch");
}
}
使用 catch 中的 continue 输出
Outer loop start
Inner loop start
1
In inner catch about to continue
Inner loop start
2
In inner catch about to continue
Inner loop start
3
In inner catch about to continue
Outer loop end
Outer loop start
Inner loop start
1
In inner catch about to continue
Inner loop start
2
In inner catch about to continue
Inner loop start
3
In inner catch about to continue
Outer loop end
Outer loop start
Inner loop start
1
In inner catch about to continue
Inner loop start
2
In inner catch about to continue
Inner loop start
3
In inner catch about to continue
Outer loop end
循环变量封闭
List<Func<int>> actions = new List<Func<int>>();
int variable = 0;
while (variable < 3)
{
actions.Add(() => variable * variable);
++ variable;
}
foreach (var act in actions)
{
Console.WriteLine(act.Invoke());
}
循环封闭变量的输出
9
9
9
循环变量封闭的解决方案,复制循环变量并将其传递给操作。
while (variable < 3)
{
int copy = variable;
actions.Add(() => copy * copy );
++ variable;
}
输出
0
1
4
catch (某些异常类型) { }
- Igby Largemanl
。 - Sergey Kalinichenko