在c#foreach循环中catch {}和catch {continue;}有什么区别?

在c#foreach循环中catch {}和catch {continue;}有什么区别?

问题描述:

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


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

在这种情况下,什么也没有,因为try是循环复合语句的最后一个语句。 continue将始终转到下一次迭代,或者如果条件不再成立,则结束循环。

catch { continue; }将导致代码在新的迭代上启动,跳过循环内的catch块之后的任何代码。

编译器会忽略它。这是从反射器。

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 
     { 
     } 
    } 
} 
+2

这可能是由编译器完成的优化。上面的示例代码非常具体。如果在catch块之后(在第二个foreach循环中)有语句,那么你应该看到继续。所以你不能说,总是继续被忽略。 – SysAdmin 2010-06-10 19:06:58

+0

@SysAdmin - 我很好奇你为什么发表了这个评论,当我的回答没有提到'继续'将永远被忽略。 – ChaosPandion 2010-06-11 04:11:28

其他答案告诉你在给定的代码片段中会发生什么。使用catch子句作为循环中的最终代码,没有功能差异。如果你有catch子句后面的代码,那么没有“continue”的版本将执行该代码。 continuebreak的stepbrother,它将循环体的其余部分短路。与continue,它跳到下一个迭代,而break完全退出循环。无论如何,为自己展示你的两种行为。

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"); 
} 

如果您的样本是逐字记录的,那么我会说“没有区别”!

但是,如果您在发现后执行语句,那么它就完全不同了!
catch { continue; }将跳过catch块之后的任何东西!
catch{}仍然会执行catch块后的语句!