HOW TO:使用 Catch 區塊中的特定例外狀況
更新:2007 年 11 月
當例外狀況發生時,它會在堆疊中向上傳遞,而讓各個 Catch 區塊都有機會來處理它。Catch 陳述式的順序很重要。請針對特定例外狀況將 Catch 區塊放在一般例外狀況 Catch 區塊之前,否則編譯器 (Compiler) 可能會發出錯誤。適當的 Catch 區塊會藉著將 Catch 區塊中指定的例外狀況名稱與例外狀況類型作比對來決定。如果沒有特定的 Catch 區塊,例外狀況由一般 Catch 區塊 (若有一個的話) 來攔截。
下列程式碼範例使用 Try/Catch 區塊來攔截 InvalidCastException。範例建立稱為 Employee 的類別,它具有單一屬性「員工職等」(Emlevel)。方法 , PromoteEmployee 會接受物件並增加員工職等。當 DateTime 執行個體傳遞至 PromoteEmployee 方法時,就會發生 InvalidCastException。
範例
Imports System
Public Class Employee
'Create employee level property.
Public Property Emlevel() As Integer
Get
Return emlevel
End Get
Set
emlevel = value
End Set
End Property
Private emlevel As Integer
End Class 'Employee
Public Class Ex13
Public Shared Sub PromoteEmployee(emp As [Object])
'Cast object to Employee.
Dim e As Employee = CType(emp, Employee)
' Increment employee level.
e.Emlevel = e.Emlevel + 1
End Sub 'PromoteEmployee
Public Shared Sub Main()
Try
Dim o = New Employee()
Dim newyears As New DateTime(2001, 1, 1)
'Promote the new employee.
PromoteEmployee(o)
'Promote DateTime; results in InvalidCastException as newyears is not an employee instance.
PromoteEmployee(newyears)
Catch e As InvalidCastException
Console.WriteLine(("Error passing data to PromoteEmployee method. " + e))
End Try
End Sub 'Main
End Class 'Ex13
using System;
public class Employee
{
//Create employee level property.
public int Emlevel
{
get
{
return(emlevel);
}
set
{
emlevel = value;
}
}
int emlevel;
}
public class Ex13
{
public static void PromoteEmployee(Object emp)
{
//Cast object to Employee.
Employee e = (Employee) emp;
// Increment employee level.
e.Emlevel = e.Emlevel + 1;
}
public static void Main()
{
try
{
Object o = new Employee();
DateTime newyears = new DateTime(2001, 1, 1);
//Promote the new employee.
PromoteEmployee(o);
//Promote DateTime; results in InvalidCastException as newyears is not an employee instance.
PromoteEmployee(newyears);
}
catch (InvalidCastException e)
{
Console.WriteLine("Error passing data to PromoteEmployee method. " + e);
}
}
}
Common Language Runtime 會攔截未被 Catch 區塊攔截的例外狀況。取決於執行階段如何被設定,不是偵錯對話方塊出現,就是程式停止執行而出現帶有例外狀況資訊的對話方塊。如需偵錯的詳細資訊,請參閱偵錯和分析應用程式。