开发者

What's the difference between catch {} and catch {continue;} in a c# foreach loop?

开发者 https://www.devze.com 2023-01-02 20:38 出处:网络
foreach (Widget item in items) { try { //do something... } catch { } } foreach (Widget item in items) { try
foreach (Widget item in items)
{
 try
 {
  //do something...
 }
 catch { }
}


foreach (Widget item in items)
{
 try
 {
  //do something...
 开发者_开发知识库}
 catch { continue; }
}


catch { continue; } will cause the code to start on a new iteration, skipping any code after the catch block within the loop.


The other answers tell you what will happen in your given snippet. With your catch clause being the final code in the loop, there's no functional difference. If you had code that followed the catch clause, then the version without "continue" would execute that code. continue is the stepbrother of break, it short circuits the rest of the loop body. With continue, it skips to the next iteration, while break exits the loop entirely. At any rate, demonstrate your two behaviors for yourself.

for (int i = 0; i < 10; i++)
{
    try
    {
        throw new Exception();
    }
    catch
    {
    }

    Console.WriteLine("I'm after the exception");
}

for (int i = 0; i < 10; i++)
{
    try
    {
        throw new Exception();
    }
    catch
    {
        continue;
    }

    Console.WriteLine("this code here is never called");
}


In that case, nothing, since the try is the last statement of the loop compound statement. continue will always go to the next iteration, or end the loop if the condition no longer holds.


The compiler will ignore it. This was taken from Reflector.

public static void Main(string[] arguments)
{
    foreach (int item in new int[] { 1, 2, 3 })
    {
        try
        {
        }
        catch
        {
        }
    }
    foreach (int item in new int[] { 1, 2, 3 })
    {
        try
        {
        }
        catch
        {
        }
    }
}


If your sample is followed verbatim, then, I would say "no difference"!

But, if you have statements to be executed after your catch then it is a different game altogether!
catch { continue; } will skip anything after the catch block!!!
catch{} will still execute the statements after the catch block!!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号