在这种情况下(在C#中),finally会被执行吗?
try
{
// Do something.
}
catch
{
// Rethrow the exception.
throw;
}
finally
{
// Will this part be executed?
}
在这种情况下(在C#中),finally会被执行吗?
try
{
// Do something.
}
catch
{
// Rethrow the exception.
throw;
}
finally
{
// Will this part be executed?
}
是的,finally块总是会被执行。
一个演示其行为的简单例子:
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");
}
}
最终块始终会被执行。我所知道的唯一例外情况是:
大多数Finally未被执行的情况与灾难性故障有关,除了后台线程之外,因此特别值得注意。
是的。
你可以轻松地测试这个。
但是,你提出这个问题的事实本身就是在为将其编写为try/catch块内嵌于try/finally中进行辩护。这样更易于阅读。