更新:2007 年 11 月
下列指南有助于确保正确设计您的自定义异常。
避免使用深的异常层次结构。
有关更多信息,请参见类型和命名空间。
一定要从 System.Exception 或其他常见基本异常之一派生异常。
请注意,捕捉和引发标准异常类型具有一个指南,指出不应从 ApplicationException 派生自定义异常。
异常类名称一定要以后缀 Exception 结尾。
一致的命名约定有助于降低新库的学习曲线。
应使异常可序列化。异常必须可序列化才能跨越应用程序域和远程处理边界正确工作。
有关使类型可序列化的更多信息,请参见序列化。
一定要在所有异常上都提供(至少是这样)下列常见构造函数。确保参数的名称和类型与在下面的代码示例中使用的那些相同。
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.
}
}
考虑提供异常属性,以便可以以编程方式访问除消息字符串之外与异常相关的额外信息。
部分版权所有 2005 Microsoft Corporation。保留所有权利。
部分版权所有 Addison-Wesley Corporation。保留所有权利。
有关设计指南的更多信息,请参见 Krzysztof Cwalina 和 Brad Abrams 编著、Addison-Wesley 于 2005 年出版的“Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries”(《框架设计指南:可重用 .NET 库的约定、术语和模式》)。