您可以使用bool
可变标志catch块设置和执行继续抓后声明,如果标志指示catch块的执行。
foreach (string l in lUserName)
{
bool isError = false; //flag would remain flase if no exception occurs
try
{
newMessages = FetchUnseenMessages();
}
catch
{
isError = true;
}
if(isError) continue; //flag would be true if exception occurs
//Other code
}
如果继续语句退出具有相关联的最后 块的一个或多个try块,则控制最初转移到最内层的try语句的最后块 。当和如果控制到达最后一个块的末尾 点,则控制转移到下一个包围try语句的最后一个块 。重复此过程直到 所有干预尝试语句的最后块都执行 ,msdn。
编辑通过所提供的资料的继续应该是不正常的,你不应该有任何问题的行为。您可能还有其他问题,如closure variable in a loop,您可以阅读更多关于变量关闭here。
我做了一个测试来验证给定的情况,它似乎是正常的。
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");
}
}
继续使用在捕获的输出
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(SomeExceptionTypeType){}' –
l没有被传入你的方法。那么是什么让你认为错误的循环正在运行? – Aron
“我不认为继续声明会转到foreach声明中的下一个项目”你怎么知道的?你的代码甚至不使用'l'。 – dasblinkenlight