You can use a bool
variable flag set in catch block and execute continue statement after catch if flag indicates the execution of catch block.
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
}
If the continue statement exits one or more try blocks with associated
finally blocks, control is initially transferred to the finally block
of the innermost try statement. When and if control reaches the end
point of a finally block, control is transferred to the finally block
of the next enclosing try statement. This process is repeated until
the finally blocks of all intervening try statements have been
executed, msdn.
Edit By the given details the behaviour of the continue should be normal not you should not have any problems. You might have some other problem like closure variable in a loop, you can read more about variable closure here.
I have made a test to verify the given scenario and it appears to be normal.
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");
}
}
The output using continue in 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
Loop variable enclosure
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());
}
Output of loop enclosure variable
9
9
9
Solution of loop variable enclosure, make a copy of loop variable and pass it to action.
while (variable < 3)
{
int copy = variable;
actions.Add(() => copy * copy );
++ variable;
}
Output
0
1
4