更新 : 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.
}
}
メッセージ文字列に加え、例外に関連する補足情報にプログラムでアクセスするための例外プロパティを提供することを検討します。
Portions Copyright 2005 Microsoft Corporation.All rights reserved.
Portions Copyright Addison-Wesley Corporation.All rights reserved.
デザイン ガイドラインの詳細については、2005 年に Addison-Wesley から出版されている Krzysztof Cwalina、Brad Abrams 共著の『Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries』を参照してください。