Share via


设计自定义异常

下列指南有助于确保正确设计您的自定义异常。

避免使用深的异常层次结构。

有关更多信息,请参见类型和命名空间

一定要从 System.Exception 或其他常见基本异常之一派生异常。

请注意,捕捉和引发标准异常类型 具有一个指南,指出不应从 ApplicationException 派生自定义异常。

异常类名称一定要以后缀 Exception 结尾。

一致的命名约定有助于降低新库的学习曲线。

应使异常可序列化。 异常必须可序列化才能跨越应用程序域和远程处理边界正确工作。

有关使类型可序列化的更多信息,请参见 Serialization

一定要在所有异常上都提供(至少是这样)下列常见构造函数。 确保参数的名称和类型与在下面的代码示例中使用的那些相同。

Public Class NewException
    Inherits BaseException
    Implements ISerializable

    Public Sub New()
        MyBase.New()
        ' Add implementation.
    End Sub

    Public Sub New(ByVal message As String)
        MyBase.New()
        ' Add implementation.
    End Sub

    Public Sub New(ByVal message As String, ByVal inner As Exception)
        MyBase.New()
        ' Add implementation.
    End Sub

    ' This constructor is needed for serialization.
    Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        MyBase.New()
        ' Add implementation.
    End Sub
End Class
public class NewException : BaseException, ISerializable
{
    public NewException()
    {
        // Add implementation.
    }
    public NewException(string message)
    {
        // Add implementation.
    }
    public NewException(string message, Exception inner)
    {
        // Add implementation.
    }

    // This constructor is needed for serialization.
   protected NewException(SerializationInfo info, StreamingContext context)
   {
        // Add implementation.
   }
}
public ref class NewException : BaseException, ISerializable
{
public:
    NewException()
    {
        // Add implementation.
    }

    NewException(String^ message)
    {
        // Add implementation.
    }

    NewException(String^ message, Exception^ inner)
    {
        // Add implementation.
    }

protected:
    // This constructor is needed for serialization.
    NewException(SerializationInfo info, StreamingContext context)
    {
        // Add implementation.
    }
};

一定要只在要求适合的权限后,才通过 System.Object.ToString 的重写报告安全敏感信息。 如果权限要求失败,则返回一个不包括安全敏感信息的字符串。

一定要以私有异常状态存储有用的安全敏感信息。 请确保只有受信任的代码才能获取该信息。

考虑提供异常属性,以便可以以编程方式访问除消息字符串之外与异常相关的额外信息。

部分版权所有 2005 Microsoft Corporation。 保留所有权利。

部分版权所有 Addison-Wesley Corporation。 保留所有权利。

设计指引的详细信息,请参阅"框架设计准则: 公约、 成语和可重复使用的模式。网络图书馆"书 Krzysztof Cwalina 和布拉德 · 艾布拉姆斯,2005年艾迪生 - 韦斯利,发表。

请参见

概念

选择要引发的正确异常类型

其他资源

类库开发的设计准则

异常设计准则