如何创建用户定义的异常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

备注

使用远程处理时,必须确保所有用户定义的异常的元数据在服务器(被调用方)可用,在客户端(代理对象或调用方)也可用。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