异常

2009-05-23 91 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