下列方針可協助您確保自訂例外狀況有正確的設計。
避免使用深層例外狀況階層架構。
如需詳細資訊,請參閱型別和命名空間。
要從 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 的覆寫來報告有安全性顧慮的資訊。 如果使用權限要求失敗,則會傳回一個不包括有安全性顧慮之資訊的字串。
要在私用例外狀況狀態下儲存有安全性顧慮的實用資訊; 確定只有信任的程式碼才能取得此資訊。
要考慮提供例外狀況屬性,以便能夠以程式設計方式存取與此例外狀況相關的額外資訊 (除了訊息字串外)。
Portions Copyright 2005 Microsoft Corporation. All rights reserved.
Portions Copyright Addison-Wesley Corporation. All rights reserved.
設計指引的詳細資訊,請參閱"框架設計準則:公約、 成語和可重複使用的模式。網路圖書館"書 Krzysztof Cwalina 和布拉德 · 艾布拉姆斯,2005年艾迪生 - 衛斯理,發表。