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

IDictionary 인터페이스를 구현하며 사용자 정의 키/값 쌍의 컬렉션을 포함하는 개체입니다. 기본값은 빈 컬렉션입니다.

예제

다음 예제에서는 속성을 사용 하 여 정보를 추가 하 고 검색 하는 방법을 보여 줍니다 Data .

using namespace System;
using namespace System::Collections;

void NestedRunTest( bool displayDetails ); // forward declarations
void NestedRoutine1( bool displayDetails );
void NestedRoutine2( bool displayDetails );
void RunTest( bool displayDetails );

int main()
{
   Console::WriteLine("\nException with some extra information..." );
   RunTest(false);
   Console::WriteLine("\nException with all extra information..." );
   RunTest(true);
}

void RunTest( bool displayDetails )
{
   try
   {
      NestedRoutine1( displayDetails );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "An exception was thrown." );
      Console::WriteLine( e->Message );
      if ( e->Data != nullptr )
      {
         Console::WriteLine( "  Extra details:" );

         for each (DictionaryEntry de in e->Data)
            Console::WriteLine("    Key: {0,-20}      Value: {1}", 
                               "'" + de.Key->ToString() + "'", de.Value);
      }
   }
}

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;
   }
}

void NestedRoutine2( bool displayDetails )
{
   Exception^ e = gcnew 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;
}

/*
This example produces the following results:

Exception with some extra information...
An exception was thrown.
This statement is the original exception message.
  Extra details:
    The key is 'ExtraInfo' and the value is: Information from NestedRoutine1.
    The key is 'MoreExtraInfo' and the value is: More information from NestedRoutine1.

Exception with all extra information...
An exception was thrown.
This statement is the original exception message.
  Extra details:
    The key is 'stringInfo' and the value is: Information from NestedRoutine2.
    The key is 'IntInfo' and the value is: -903
    The key is 'DateTimeInfo' and the value is: 11/26/2002 2:12:58 PM
    The key is 'ExtraInfo' and the value is: Information from NestedRoutine1.
    The key is 'MoreExtraInfo' and the value is: More information from NestedRoutine1.
*/
// 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 안전하지 않습니다. 애플리케이션이 중첩 된 일련의 루틴을 호출 하는 경우 예외 처리기를 포함 하는 각 루틴 결과 호출 스택의 해당 예외 처리기의 계층 구조를 포함 합니다. 하위 수준 루틴에서 예외를 throw하는 경우 호출 스택 계층 구조의 상위 수준 예외 처리기는 다른 예외 처리기에서 컬렉션에 저장된 키/값 쌍을 읽고/또는 수정할 수 있습니다. 즉, 키/값 쌍의 정보는 기밀 및 애플리케이션의 키/값 쌍에서 정보를 손상 된 경우 제대로 작동 되도록 해야 합니다.

주요 충돌

키 충돌은 다른 예외 처리기가 키/값 쌍에 액세스하기 위해 동일한 키를 지정하는 경우에 발생합니다. 키 충돌의 결과 하위 수준의 예외 처리기 더 높은 수준의 예외 처리기를 사용 하 여 실수로 통신할 수 있고이 통신에는 미묘한 프로그램 오류가 발생할 수 있습니다 되었기 때문에 애플리케이션을 개발 하는 경우에 주의 해야 합니다. 그러나 기울인다면 애플리케이션을 강화 하기 위해 키 충돌을 사용할 수 있습니다.

키 충돌 방지

키/값 쌍에 대한 고유 키를 생성하는 명명 규칙을 채택하여 키 충돌을 방지합니다. 예를 들어, 애플리케이션의 마침표로 구분 된 이름으로 구성 된 키, 쌍 및 고유 식별자에 대 한 보충 정보를 제공 하는 메서드 명명 규칙을 생성할 수 있습니다.

두 애플리케이션 제품 및 공급 업체 라는 가정 각각에 Sales 라는 메서드가 있습니다. 제품 애플리케이션에서 Sales 메서드는 제품의 id 번호 (stock keeping unit 또는 SKU)를 제공 합니다. 공급 업체 애플리케이션에서 Sales 메서드 id 번호 또는 공급자의 SID를 제공합니다. 따라서 이 예제의 명명 규칙은 "Products.Sales.SKU" 및 "Suppliers.Sales.SID" 키를 생성합니다.

주요 충돌 악용

하나 이상의 특수한 미리 구성된 키가 있는 경우 처리를 제어하여 키 충돌을 악용합니다. 한 시나리오에서 호출 스택 계층 구조의 최고 수준 예외 처리기가 하위 수준 예외 처리기에서 throw된 모든 예외를 catch한다고 가정합니다. 특수 키가 있는 키/값 쌍이 있는 경우 상위 수준 예외 처리기는 개체의 나머지 키/값 쌍 IDictionary 의 형식을 비표준 방식으로 지정합니다. 그렇지 않으면 나머지 키/값 쌍의 형식이 일반적인 방식으로 지정됩니다.

이제 다른 시나리오에서 호출 스택 계층 구조의 각 수준에서 예외 처리기가 다음 하위 수준 예외 처리기에서 throw된 예외를 catch한다고 가정합니다. 또한 각 예외 처리기는 속성에서 반환된 컬렉션에 Data 미리 구성된 키 집합으로 액세스할 수 있는 키/값 쌍 집합이 포함되어 있음을 알고 있습니다.

각 예외 처리기는 미리 구성된 키 집합을 사용하여 해당 예외 처리기에 고유한 정보로 해당 키/값 쌍의 값 구성 요소를 업데이트합니다. 업데이트 프로세스가 완료되면 예외 처리기가 다음 상위 수준 예외 처리기에 예외를 throw합니다. 마지막으로, 최상위 예외 처리기는 키/값 쌍에 액세스하고 모든 하위 수준 예외 처리기의 통합 업데이트 정보를 표시합니다.

적용 대상

추가 정보