如何建立使用者定義的例外狀況How to create user-defined exceptions

.NET 提供基本上衍生自基底類別 Exception 之例外狀況類別的階層架構。.NET provides a hierarchy of exception classes ultimately derived from the base class Exception. 不過,如果沒有預先定義的例外狀況符合您的需求,您可以藉由衍生自 Exception 類別,建立您自己的例外狀況類別。However, if none of the predefined exceptions meets your needs, you can create your own exception classes by deriving from the Exception class.

建立您自己的例外狀況時,請以文字 "Exception" 作為使用者定義例外狀況類別名稱的結尾,並實作三種常見的建構函式,如下列範例所示。When creating your own exceptions, end the class name of the user-defined exception with the word "Exception", and implement the three common constructors, as shown in the following example. 此範例會定義名為 EmployeeListNotFoundException 的新例外狀況類別。The example defines a new exception class named EmployeeListNotFoundException. 此類別衍生自 Exception,包含三個建構函式。The class is derived from Exception and includes three constructors.

using namespace System;

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

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

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

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

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

    public EmployeeListNotFoundException(string message, Exception inner)
        : base(message, inner)
    {
    }
}
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

注意

在您使用遠端功能的情況下,您必須確定任何使用者定義例外狀況的中繼資料是由伺服器 (被呼叫端) 提供,並提供給用戶端 (Proxy 物件或呼叫端)。In situations where you are using remoting, you must ensure that the metadata for any user-defined exceptions is available at the server (callee) and to the client (the proxy object or caller). 如需詳細資訊,請參閱例外狀況的最佳做法For more information, see Best practices for exceptions.

另請參閱See also