是的。即使有一个Exception
insidecatch
块,finally
也会被执行。
如果您熟悉 C++,只需将其finally
视为. 无论对象中的语句处于何种状态,都将被执行。但是你不能放在[一些编译器允许] 之内。destructor
object
~Destructor
return
finally
请参阅下面的代码:查看如何y
更改全局变量。另请参阅如何Exception1
被Exception2
.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace finallyTest
{
class Program
{
static int y = 0;
static int testFinally()
{
int x = 0;
try
{
x = 1;
throw new Exception("Exception1");
x = 2;
return x;
}
catch (Exception e)
{
x = -1;
throw new Exception("Exception2", e);
}
finally
{
x = 3;
y = 1;
}
return x;
}
static void Main(string[] args)
{
try
{
Console.WriteLine(">>>>>" + testFinally());
}
catch (Exception e)
{ Console.WriteLine(">>>>>" + e.ToString()); }
Console.WriteLine(">>>>>" + y);
Console.ReadLine();
}
}
}
输出:
>>>>>System.Exception: Exception2 ---> System.Exception: Exception1
at finallyTest.Program.testFinally() in \Projects\finallyTest\finallyTest\Program.cs:line 17
--- End of inner exception stack trace ---
at finallyTest.Program.testFinally() in \Projects\finallyTest\finallyTest\Program.cs:line 24
at finallyTest.Program.Main(String[] args) in \Projects\finallyTest\finallyTest\Program.cs:line 38
>>>>>1