可能重复:
最终块未运行?
我对 C# 中的 finally 块有疑问。我写了一个小示例代码:
public class MyType
{
public void foo()
{
try
{
Console.WriteLine("Throw NullReferenceException?");
string s = Console.ReadLine();
if (s == "Y")
throw new NullReferenceException();
else
throw new ArgumentException();
}
catch (NullReferenceException)
{
Console.WriteLine("NullReferenceException was caught!");
}
finally
{
Console.WriteLine("finally block");
}
}
}
class Program
{
static void Main(string[] args)
{
MyType t = new MyType();
t.foo();
}
}
据我所知,不管是否抛出异常,finally 块都假设确定性地运行。现在,如果用户输入“Y” - 抛出 NullReferenceException,执行将移至 catch 时钟,然后移至 finally 块,如我所料。但是如果输入是别的东西 - ArgumentException 被抛出。没有合适的 catch 块来捕获这个异常,所以我认为执行应该移动 finally 块 - 但它没有。有人可以解释一下为什么吗?
感谢大家 :)