可能是重复问题:
finally块不执行??
我有一个关于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块-但实际上并没有。请有人可以解释一下原因吗?谢谢大家 :)