異常

2009-05-23 96 views
3

可能重複:
In C# will the Finally block be executed in a try, catch, finally if an unhandled exception is thrown ?異常

,最終會在這種情況下執行的(在C#)?

try 
{ 
    // Do something. 
} 
catch 
{ 
    // Rethrow the exception. 
    throw; 
} 
finally 
{ 
    // Will this part be executed? 
} 
+0

看到這個副本(或其中一個其他重複鏈接在那裏):http://stackoverflow.com/questions/833946/in-c-will-the-finally-block-be-executed-in-a-try -catch-finally-if-an-unhandled – 2009-05-23 08:55:25

回答

11

是的,終於總是執行。

用於演示的行爲一個簡單的例子:

private void Button_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     ThrowingMethod(); 
    } 
    catch 
    { 
    } 
} 

private void ThrowingMethod() 
{ 
    try 
    { 
     throw new InvalidOperationException("some exception"); 
    } 
    catch 
    { 
     throw; 
    } 
    finally 
    { 
     MessageBox.Show("finally"); 
    } 
} 
1

是。

你可以很容易地測試出來。

但是你問這個問題的一個很好的論點是把它作爲一個嵌套在try/finally中的try/catch塊編寫的好的參數。在眼睛上更容易。

3

(編輯:澄清從評論納入 - 謝謝你們)
最後總是執行。我知道的唯一例外是;

  • 你拔電源插頭
  • 如果運行的「後臺」線程被終止,因爲主程序其所屬的結束,最終在該線程塊將不被執行。見Joseph Albahari
  • 其他異步異常像堆棧溢出和內存不足。見this question

最後沒有執行的大多數場景都與catastrohic失敗有關,除了後臺線程之外,所以值得特別注意。

+0

看到相關的答案:http://stackoverflow.com/questions/833946/in-c-will-the-finally-block-be-executed-in-a-try-如果未處理,最終捕捉到「 – 2009-05-23 08:54:45