Exception.Data プロパティ

定義

例外に関する追加のユーザー定義情報を提供するキーと値のペアのコレクションを取得します。

public:
 virtual property System::Collections::IDictionary ^ Data { System::Collections::IDictionary ^ get(); };
public virtual System.Collections.IDictionary Data { get; }
member this.Data : System.Collections.IDictionary
Public Overridable ReadOnly Property Data As IDictionary

プロパティ値

IDictionary インターフェイスを実装し、ユーザー定義のキーと値のペアのコレクションを含むオブジェクト。 既定値は空のコレクションです。

次の例では、 Data プロパティを使用して情報を追加および取得する方法を示します。

// This example demonstrates the Exception.Data property.
using System;
using System.Collections;

class Sample
{
   public static void Main()
   {
      Console.WriteLine("\nException with some extra information...");
      RunTest(false);
      Console.WriteLine("\nException with all extra information...");
      RunTest(true);
   }

   public static void RunTest(bool displayDetails)
   {
      try {
         NestedRoutine1(displayDetails);
      }
      catch (Exception e) {
         Console.WriteLine("An exception was thrown.");
         Console.WriteLine(e.Message);
         if (e.Data.Count > 0) {
            Console.WriteLine("  Extra details:");
            foreach (DictionaryEntry de in e.Data)
               Console.WriteLine("    Key: {0,-20}      Value: {1}",
                                 "'" + de.Key.ToString() + "'", de.Value);
         }
      }
   }

   public static void NestedRoutine1(bool displayDetails)
   {
      try {
         NestedRoutine2(displayDetails);
      }
      catch (Exception e) {
         e.Data["ExtraInfo"] = "Information from NestedRoutine1.";
         e.Data.Add("MoreExtraInfo", "More information from NestedRoutine1.");
         throw;
      }
   }

   public static void NestedRoutine2(bool displayDetails)
   {
      Exception e = new Exception("This statement is the original exception message.");
      if (displayDetails) {
         string s = "Information from NestedRoutine2.";
         int i = -903;
         DateTime dt = DateTime.Now;
         e.Data.Add("stringInfo", s);
         e.Data["IntInfo"] = i;
         e.Data["DateTimeInfo"] = dt;
      }
      throw e;
   }
}
// The example displays the following output:
//    Exception with some extra information...
//    An exception was thrown.
//    This statement is the original exception message.
//      Extra details:
//        Key: 'ExtraInfo'               Value: Information from NestedRoutine1.
//        Key: 'MoreExtraInfo'           Value: More information from NestedRoutine1.
//
//    Exception with all extra information...
//    An exception was thrown.
//    This statement is the original exception message.
//      Extra details:
//        Key: 'stringInfo'              Value: Information from NestedRoutine2.
//        Key: 'IntInfo'                 Value: -903
//        Key: 'DateTimeInfo'            Value: 7/29/2013 10:50:13 AM
//        Key: 'ExtraInfo'               Value: Information from NestedRoutine1.
//        Key: 'MoreExtraInfo'           Value: More information from NestedRoutine1.
// This example demonstrates the Exception.Data property.
open System
open System.Collections

let nestedRoutine2 displayDetails =
    let e = Exception "This statement is the original exception message."
    if displayDetails then
        let s = "Information from nestedRoutine2."
        let i = -903
        let dt = DateTime.Now
        e.Data.Add("stringInfo", s)
        e.Data["IntInfo"] <- i
        e.Data["DateTimeInfo"] <- dt
    raise e

let nestedRoutine1 displayDetails =
    try
        nestedRoutine2 displayDetails
    with e ->
        e.Data["ExtraInfo"] <- "Information from nestedRoutine1."
        e.Data.Add("MoreExtraInfo", "More information from nestedRoutine1.")
        reraise ()

let runTest displayDetails =
    try
        nestedRoutine1 displayDetails
    with e ->
        printfn "An exception was thrown."
        printfn $"{e.Message}"
        if e.Data.Count > 0 then
            printfn "  Extra details:"
            for de in e.Data do
                let de = de :?> DictionaryEntry
                printfn $"""    Key: {"'" + de.Key.ToString() + "'",-20}      Value: {de.Value}"""

printfn "\nException with some extra information..."
runTest false
printfn "\nException with all extra information..."
runTest true

   
// The example displays the following output:
//    Exception with some extra information...
//    An exception was thrown.
//    This statement is the original exception message.
//      Extra details:
//        Key: 'ExtraInfo'               Value: Information from NestedRoutine1.
//        Key: 'MoreExtraInfo'           Value: More information from NestedRoutine1.
//
//    Exception with all extra information...
//    An exception was thrown.
//    This statement is the original exception message.
//      Extra details:
//        Key: 'stringInfo'              Value: Information from NestedRoutine2.
//        Key: 'IntInfo'                 Value: -903
//        Key: 'DateTimeInfo'            Value: 7/29/2013 10:50:13 AM
//        Key: 'ExtraInfo'               Value: Information from NestedRoutine1.
//        Key: 'MoreExtraInfo'           Value: More information from NestedRoutine1.
Imports System.Collections

Module Example
   Public Sub Main()
      Console.WriteLine()
      Console.WriteLine("Exception with some extra information...")
      RunTest(False)
      Console.WriteLine()
      Console.WriteLine("Exception with all extra information...")
      RunTest(True)
   End Sub

   Public Sub RunTest(displayDetails As Boolean)
      Try
         NestedRoutine1(displayDetails)
      Catch e As Exception
         Console.WriteLine("An exception was thrown.")
         Console.WriteLine(e.Message)
         If e.Data.Count > 0 Then
            Console.WriteLine("  Extra details:")
            For Each de As DictionaryEntry In e.Data
               Console.WriteLine("    Key: {0,-20}      Value: {1}",
                                 "'" + de.Key.ToString() + "'", de.Value)
            Next
         End If 
      End Try 
   End Sub 

   Public Sub NestedRoutine1(displayDetails As Boolean)
      Try
         NestedRoutine2(displayDetails)
      Catch e As Exception
         e.Data("ExtraInfo") = "Information from NestedRoutine1."
         e.Data.Add("MoreExtraInfo", "More information from NestedRoutine1.")
         Throw e
      End Try 
   End Sub

   Public Sub NestedRoutine2(displayDetails As Boolean)
      Dim e As New Exception("This statement is the original exception message.")
      If displayDetails Then 
         Dim s As String = "Information from NestedRoutine2." 
         Dim i As Integer = -903
         Dim dt As DateTime = DateTime.Now
         e.Data.Add("stringInfo", s)
         e.Data("IntInfo") = i
         e.Data("DateTimeInfo") = dt
      End If 
      Throw e
   End Sub 
End Module
' This example displays the following output: 
'    Exception with some extra information...
'    An exception was thrown.
'    This statement is the original exception message.
'      Extra details:
'        Key: 'ExtraInfo'               Value: Information from NestedRoutine1.
'        Key: 'MoreExtraInfo'           Value: More information from NestedRoutine1.
'    
'    Exception with all extra information...
'    An exception was thrown.
'    This statement is the original exception message.
'      Extra details:
'        Key: 'stringInfo'              Value: Information from NestedRoutine2.
'        Key: 'IntInfo'                 Value: -903
'        Key: 'DateTimeInfo'            Value: 7/29/2013 10:50:13 AM
'        Key: 'ExtraInfo'               Value: Information from NestedRoutine1.
'        Key: 'MoreExtraInfo'           Value: More information from NestedRoutine1.

注釈

例外に関連する補足情報を格納および取得するには、System.Collections.IDictionary プロパティによって返されるData オブジェクトを使用します。 この情報は、任意の数のユーザー定義キーと値のペアの形式です。 各キー/値ペアのキー コンポーネントは通常、識別文字列ですが、ペアの値コンポーネントは任意の種類のオブジェクトにすることができます。

キーと値のペアのセキュリティ

Data プロパティによって返されるコレクションに格納されているキーと値のペアは安全ではありません。 アプリケーションが入れ子になった一連のルーチンを呼び出し、各ルーチンに例外ハンドラーが含まれている場合、結果の呼び出し履歴にはそれらの例外ハンドラーの階層が含まれます。 下位レベルのルーチンが例外をスローした場合、呼び出し履歴階層の上位レベルの例外ハンドラーは、他の例外ハンドラーによってコレクションに格納されているキーと値のペアを読み取ったり変更したりできます。 つまり、キーと値のペアの情報が機密ではなく、キーと値のペアの情報が破損している場合にアプリケーションが正しく動作することを保証する必要があります。

主要な対立

異なる例外ハンドラーが同じキーを指定してキーと値のペアにアクセスすると、キーの競合が発生します。 重要な競合の結果として、下位レベルの例外ハンドラーが誤って上位レベルの例外ハンドラーと通信する可能性があり、この通信によって微妙なプログラム エラーが発生する可能性があるため、アプリケーションの開発には注意が必要です。 ただし、注意が必要な場合は、キーの競合を使用してアプリケーションを強化できます。

キーの競合を回避する

キーと値のペアの一意のキーを生成する名前付け規則を採用することで、キーの競合を回避します。 たとえば、名前付け規則では、アプリケーションのピリオドで区切られた名前、ペアの補足情報を提供するメソッド、および一意の識別子で構成されるキーが生成される場合があります。

Products と Suppliers という名前の 2 つのアプリケーションに、それぞれ Sales という名前のメソッドがあるとします。 製品アプリケーションの Sales メソッドは、製品の識別番号 (在庫保管単位または SKU) を提供します。 Suppliers アプリケーションの Sales メソッドは、仕入先の ID 番号 (SID) を提供します。 したがって、この例の名前付け規則では、キー "Products.Sales.SKU" と "Suppliers.Sales.SID" が生成されます。

重要な対立を利用する

処理を制御するために、1 つ以上の特別な事前に配列されたキーの存在を使用して、キーの競合を悪用します。 あるシナリオでは、呼び出し履歴階層の最上位レベルの例外ハンドラーが、下位レベルの例外ハンドラーによってスローされたすべての例外をキャッチするとします。 特殊なキーを持つキーと値のペアが存在する場合、高レベルの例外ハンドラーは、 IDictionary オブジェクト内の残りのキーと値のペアを何らかの非標準の方法で書式設定します。それ以外の場合、残りのキーと値のペアは通常の方法で書式設定されます。

次に、別のシナリオでは、呼び出し履歴階層の各レベルの例外ハンドラーが、次の下位レベルの例外ハンドラーによってスローされた例外をキャッチするとします。 さらに、各例外ハンドラーは、 Data プロパティによって返されるコレクションに、事前に設定されたキーのセットでアクセスできる一連のキーと値のペアが含まれていることを認識しています。

各例外ハンドラーは、事前に配列されたキーのセットを使用して、対応するキーと値のペアの値コンポーネントを、その例外ハンドラーに固有の情報で更新します。 更新プロセスが完了すると、例外ハンドラーは次の上位レベルの例外ハンドラーに例外をスローします。 最後に、最上位レベルの例外ハンドラーは、キーと値のペアにアクセスし、すべての下位レベルの例外ハンドラーからの統合更新情報を表示します。

適用対象

こちらもご覧ください