try-finally (C# 參考)
使用 finally
區塊,即可清除 try 區塊中所配置的任何資源,以及執行程式碼,即使 try
區塊中發生例外狀況也是一樣。 一般而言,會在控制權離開 try
陳述式時,執行 finally
區塊的陳述式。 控制權轉移可能是正常執行、執行 break
、continue
、goto
或 return
陳述式,或是傳播 try
陳述式的例外狀況所造成。
在處理的例外狀況內,一定會執行關聯的 finally
區塊。 不過,如果無法處理例外狀況,則執行 finally
區塊取決於如何觸發例外狀況回溯作業。 接著,取決於您電腦的設定方式。 唯一不會執行 子句的情況 finally
,涉及立即停止程式。 其中一個範例是因為 InvalidProgramException IL 語句損毀而擲回時。 在大部分的作業系統上,合理的資源清除會在停止和卸載程式時進行。
通常,未處理的例外狀況結束應用程式時,是否執行 finally
區塊並不重要。 不過,如果您的 finally
區塊中有即使在這種情況下都必須執行的陳述式,則其中一個解決方案是將 catch
區塊新增至 try
-finally
陳述式。 或者,您可以攔截可能會在呼叫堆疊較高之 try
-finally
陳述式的 try
區塊中擲回的例外狀況。 亦即,您可以攔截下列方法中的例外狀況:呼叫包含 try
-finally
陳述式的方法、呼叫該方法的方法,或呼叫堆疊的任何方法。 如果未攔截到例外狀況,則執行 finally
區塊取決於作業系統是否選擇觸發例外狀況回溯作業。
範例
在下列範例中,無效的轉換陳述式會導致 System.InvalidCastException
例外狀況。 例外狀況未進行處理。
public class ThrowTestA
{
public static void Main()
{
int i = 123;
string s = "Some string";
object obj = s;
try
{
// Invalid conversion; obj contains a string, not a numeric type.
i = (int)obj;
// The following statement is not run.
Console.WriteLine("WriteLine at the end of the try block.");
}
finally
{
// To run the program in Visual Studio, type CTRL+F5. Then
// click Cancel in the error dialog.
Console.WriteLine("\nExecution of the finally block after an unhandled\n" +
"error depends on how the exception unwind operation is triggered.");
Console.WriteLine("i = {0}", i);
}
}
// Output:
// Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
//
// Execution of the finally block after an unhandled
// error depends on how the exception unwind operation is triggered.
// i = 123
}
在下列範例中,會攔截到來自呼叫堆疊最遠的方法中之 TryCast
方法的例外狀況。
public class ThrowTestB
{
public static void Main()
{
try
{
// TryCast produces an unhandled exception.
TryCast();
}
catch (Exception ex)
{
// Catch the exception that is unhandled in TryCast.
Console.WriteLine
("Catching the {0} exception triggers the finally block.",
ex.GetType());
// Restore the original unhandled exception. You might not
// know what exception to expect, or how to handle it, so pass
// it on.
throw;
}
}
static void TryCast()
{
int i = 123;
string s = "Some string";
object obj = s;
try
{
// Invalid conversion; obj contains a string, not a numeric type.
i = (int)obj;
// The following statement is not run.
Console.WriteLine("WriteLine at the end of the try block.");
}
finally
{
// Report that the finally block is run, and show that the value of
// i has not been changed.
Console.WriteLine("\nIn the finally block in TryCast, i = {0}.\n", i);
}
}
// Output:
// In the finally block in TryCast, i = 123.
// Catching the System.InvalidCastException exception triggers the finally block.
// Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
}
如需 finally
的詳細資訊,請參閱 try-catch-finally。
C# 也會包含 using 陳述式,以透過方便使用的語法提供 IDisposable 物件的類似功能。
C# 語言規格
如需詳細資訊,請參閱 C# 語言規格的 try 陳述式一節。