カスタム例外のデザイン

カスタム例外を正しくデザインするには、次のガイドラインに従います。

例外の階層構造を深くすることは避けます。

詳細については、「型と名前空間」を参照してください。

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.

設計ガイドラインの詳細についてを参照してください、「フレームワークの設計ガイドライン。規則、慣用句、および再利用可能なパターン。ネット ライブラリ」本クシシュトフ Cwalina、ブラッド エイブラムス、アスキー、2005 年発表しました。

参照

概念

スローする正しい種類の例外の選択

その他の技術情報

クラス ライブラリ開発のデザイン ガイドライン

例外のデザインのガイドライン