是的。即使在catch
區塊內有Exception
,finally
也會執行。
如果您熟悉C++,請將finally
設爲object
的destructor
。對象中的聲明狀態~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
第一個案例並不奇怪。這就是'終於'的意義。請參閱http://stackoverflow.com/questions/65035/in-java-does-return-trump-finally。 – kennytm 2010-06-03 19:38:49
你看,我期望'return'超出try/catch/finally'塊的範圍並應用於該方法。我並不是說這樣做是錯誤的,但它讓我無法理解。這只是我從未關注過的東西。我想我一直把我的方法一直貫徹到最後;) – lewiguez 2010-06-03 19:51:53