2010-06-10 206 views
6
foreach (Widget item in items) 
{ 
try 
{ 
    //do something... 
} 
catch { } 
} 


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

回答

8

在這種情況下,什麼也沒有,因爲try是循環複合語句的最後一個語句。 continue將始終轉到下一次迭代,或者如果條件不再成立,則結束循環。

20

catch { continue; }將導致代碼在新的迭代上啓動,跳過循環內的catch塊之後的任何代碼。

3

編譯器會忽略它。這是從反射器。

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

9

其他答案告訴你在給定的代碼片段中會發生什麼。使用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"); 
} 
0

如果您的樣本是逐字記錄的,那麼我會說「沒有區別」!

但是,如果您在發現後執行語句,那麼它就完全不同了!
catch { continue; }將跳過catch塊之後的任何東西!
catch{}仍然會執行catch塊後的語句!