HOW TO:使用 Finally 區塊
當例外狀況發生時,執行會停止,而控制權會交給最接近的例外處理常式。 這通常意謂著,有幾行您期待一定會被呼叫的程式碼沒有執行。 某些資源清除 (例如關閉檔案) 必須一定要執行,即使擲回例外狀況。 若要達成這點,您可以使用 Finally 區塊。 不論是否擲回例外狀況,都一定會執行 Finally 區塊。
下列程式碼範例使用 Try/Catch 區塊來攔截 ArgumentOutOfRangeException。 Main 方法建立兩個陣列,並嘗試複製其中一個給另一個。 這動作產生 ArgumentOutOfRangeException,而錯誤則寫到主控台。 Finally 區塊都會執行,不論複製動作的結果為何。
範例
Imports System
Class ArgumentOutOfRangeExample
Public Shared Sub Main()
Dim array1() As Integer = {0, 0}
Dim array2() As Integer = {0, 0}
Try
Array.Copy(array1, array2 , -1)
Catch e As ArgumentOutOfRangeException
Console.WriteLine("Error: {0}", e)
Finally
Console.WriteLine("This statement is always executed.")
End Try
End Sub
End Class
using System;
class ArgumentOutOfRangeExample
{
public static void Main()
{
int[] array1 = {0, 0};
int[] array2 = {0, 0};
try
{
Array.Copy(array1, array2, -1);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine("Error: {0}", e);
}
finally
{
Console.WriteLine("This statement is always executed.");
}
}
}
using namespace System;
ref class ArgumentOutOfRangeExample
{
public:
static void Main()
{
array<int>^ array1 = {0, 0};
array<int>^ array2 = {0, 0};
try
{
Array::Copy(array1, array2, -1);
}
catch (ArgumentOutOfRangeException^ e)
{
Console::WriteLine("Error: {0}", e);
}
finally
{
Console::WriteLine("This statement is always executed.");
}
}
};
int main()
{
ArgumentOutOfRangeExample::Main();
}