【发布时间】:2021-06-21 18:32:44
【问题描述】:
我找不到任何微软官方资源显示 finally 块下面的代码是如何执行的,关于它的唯一信息是通过 C# 编写的 CLR 一书,作者说:
如果在 try 块中没有抛出异常,或者如果 catch 块捕获到异常并且不抛出或重新抛出异常,则执行 finally 块下面的代码。
假设我们有以下代码:
class Program {
static void Main(string[] args) {
SomeMethod1();
Console.ReadLine();
}
static void SomeMethod1() {
try {
SomeMethod2();
}
finally {
Console.WriteLine("SomeMethod1 finally");
}
Console.WriteLine("SomeMethod1 last");
}
static void SomeMethod2() {
try {
SomeMethod3();
}
catch (DivideByZeroException e) {
Console.WriteLine("SomeMethod2 caught");
}
finally {
Console.WriteLine("SomeMethod2 finally");
}
Console.WriteLine("SomeMethod2 last");
}
static void SomeMethod3() {
try {
SomeMethod4();
}
finally {
Console.WriteLine("SomeMethod3 finally");
}
Console.WriteLine("SomeMethod3 last");
}
static void SomeMethod4() {
try {
Int32 i = 0;
var c = 3 / i;
}
finally {
Console.WriteLine("SomeMethod4 finally");
}
Console.WriteLine("SomeMethod4 last");
}
}
输出是:
SomeMethod4 finally
SomeMethod3 finally
SomeMethod2 caught
SomeMethod2 finally
SomeMethod2 last
SomeMethod1 finally
SomeMethod1 last
您可以看到“SomeMethod4 last”和“SomeMethod3 last”没有被打印出来。
“SomeMethod4 last”没有打印好理解,因为SomeMethod4抛出异常,并且没有catch块来捕获异常,所以不符合作者规定的要求,还算公平。
但是为什么“SomeMethod3 last”没有被打印出来? SomeMethod3 没有抛出异常,就像 SomeMethod1 一样,那么为什么打印“SomeMethod1 last”而“SomeMethod3 last”没有?是否有任何 Microsoft 官方资源可以解释其机制?
【问题讨论】: