Share via


HOW TO:建立使用者定義的例外狀況

如果您想要使用者能夠利用程式設計方式來區別某些錯誤情況,您可以建立自己的使用者定義的例外狀況。 .NET Framework 提供最終衍生自基底類別 Exception 的例外狀況類別的階層架構。 這些類別的每一個都會定義特定例外狀況,所以在許多情形中您只需攔截例外狀況即可。 您也可以藉著從 Exception 類別衍生,建立自己的 Exception 類別。

在建立您自己的例外狀況時,以文字 "Exception" 當做使用者定義的例外狀況的類別名稱結尾,是比較好的程式撰寫作法。實作三個如下列範例所示範的建議的通用建構函式 (Constructor),也是不錯的作法。

注意事項注意事項

在使用遠端處理的情形中,您必須確定伺服器 (被呼叫端) 上具有任何使用者定義的例外狀況中繼資料 (Metadata) 可供用戶端 (Proxy 物件或呼叫端) 使用。例如,呼叫不同應用程式定義域方法的程式碼必須能夠尋找含有遠端呼叫擲回的例外狀況的組件。如需詳細資訊,請參閱處理例外狀況的最佳作法

在下列範例中,新的 Exception 類別 EmployeeListNotFoundException 衍生自 Exception。 這些建構函式是在類別中定義的,每個建構函式都採用不同的參數。

範例

Imports System

Public Class EmployeeListNotFoundException
    Inherits Exception

    Public Sub New()
    End Sub

    Public Sub New(message As String)
        MyBase.New(message)
    End Sub

    Public Sub New(message As String, inner As Exception)
        MyBase.New(message, inner)
    End Sub
End Class
using System;

public class EmployeeListNotFoundException: Exception
{
    public EmployeeListNotFoundException()
    {
    }

    public EmployeeListNotFoundException(string message)
        : base(message)
    {
    }

    public EmployeeListNotFoundException(string message, Exception inner)
        : base(message, inner)
    {
    }
}
using namespace System;

public ref class EmployeeListNotFoundException : Exception
{
public:
    EmployeeListNotFoundException()
    {
    }

    EmployeeListNotFoundException(String^ message)
        : Exception(message)
    {
    }

    EmployeeListNotFoundException(String^ message, Exception^ inner)
        : Exception(message, inner)
    {
    }
};

請參閱

工作

HOW TO:使用 Try/Catch 區塊攔截例外狀況

HOW TO:使用 Catch 區塊中的特定例外狀況

概念

處理例外狀況的最佳作法

其他資源

例外處理基礎觀念