【发布时间】:2025-12-14 14:25:02
【问题描述】:
我有一个关于 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 块 - 但它没有。谁能解释一下为什么?
谢谢大家:)
【问题讨论】:
-
我试了下代码,按预期进入finally块
-
你能澄清你的意思是什么'我认为执行应该移动 finally 块' - 我认为在这两种情况下控制都进入 finally - 对吗?
-
是的,显然它确实进入了 finally 块,我错过了,因为调试器......:|
标签: c# exception-handling try-catch-finally