简体   繁体   English

ac#foreach循环中catch {}和catch {continue;}之间的区别是什么?

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

foreach (Widget item in items)
{
 try
 {
  //do something...
 }
 catch { }
}


foreach (Widget item in items)
{
 try
 {
  //do something...
 }
 catch { continue; }
}

catch { continue; } catch { continue; } will cause the code to start on a new iteration, skipping any code after the catch block within the loop. catch { continue; }会导致代码开始一个新的迭代,之后跳过任何代码catch在循环中块。

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. 使用catch子句是循环中的最终代码,没有功能差异。 If you had code that followed the catch clause, then the version without "continue" would execute that code. 如果您的代码遵循catch子句,那么没有“continue”的版本将执行该代码。 continue is the stepbrother of break , it short circuits the rest of the loop body. continuebreak的继兄,它会使循环体的其余部分短路。 With continue , it skips to the next iteration, while break exits the loop entirely. continue ,它跳到下一次迭代,而break完全退出循环。 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. 在这种情况下,没有,因为try是循环复合语句的最后一个语句。 continue will always go to the next iteration, or end the loop if the condition no longer holds. continue将始终进入下一次迭代,或者如果条件不再成立则结束循环。

The compiler will ignore it. 编译器将忽略它。 This was taken from Reflector. 这是从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; } catch { continue; } will skip anything after the catch block!!! catch { continue; }将跳过catch块后什么!
catch{} will still execute the statements after the catch block!! catch{}仍将在catch块后执行语句!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM