Exception.Data Exception.Data Exception.Data Exception.Data Property

定義

取得提供例外狀況之其他使用者定義相關資訊的索引鍵/值組集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

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 介面的物件,含有由使用者定義之索引鍵/值組所組成的集合。An object that implements the IDictionary interface and contains a collection of user-defined key/value pairs. 預設為空集合。The default is an empty collection.

範例

下列範例示範如何新增和擷取資訊使用Data屬性。The following example demonstrates how to add and retrieve information using the Data property.

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. 
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來儲存和擷取例外狀況相關的補充資訊的屬性。Use the System.Collections.IDictionary object returned by the Data property to store and retrieve supplementary information relevant to the exception. 資訊是任意數目的使用者定義索引鍵/值組的形式。The information is in the form of an arbitrary number of user-defined key/value pairs. 每個索引鍵/值組的關鍵元件通常是物件的識別的字串,而組的值元件可以是物件的任何類型。The key component of each key/value pair is typically an identifying string, whereas the value component of the pair can be any type of object.

索引鍵/值組的安全性Key/Value Pair Security

儲存在所傳回的集合中的索引鍵/值組Data屬性並不安全。The key/value pairs stored in the collection returned by the Data property are not secure. 如果您的應用程式呼叫巢狀的一連串的常式,而且每個常式包含例外狀況處理常式,則產生的呼叫堆疊會包含這些例外狀況處理常式的階層。If your application calls a nested series of routines, and each routine contains exception handlers, the resulting call stack contains a hierarchy of those exception handlers. 如果較低層級常式擲回例外狀況,呼叫堆疊階層中的任何上層例外狀況處理常式可以讀取及/或修改任何其他的例外狀況處理常式儲存在集合中的索引鍵/值組。If a lower-level routine throws an exception, any upper-level exception handler in the call stack hierarchy can read and/or modify the key/value pairs stored in the collection by any other exception handler. 這表示您必須保證中的索引鍵/值組的資訊不是機密,如果索引鍵/值組中的資訊已損毀您的應用程式將會正確運作。This means you must guarantee that the information in the key/value pairs is not confidential and that your application will operate correctly if the information in the key/value pairs is corrupted.

金鑰衝突Key Conflicts

不同的例外狀況處理常式指定相同的金鑰來存取的索引鍵/值組,就會產生索引鍵衝突。A key conflict occurs when different exception handlers specify the same key to access a key/value pair. 開發您的應用程式,因為索引鍵衝突的結果較低層級例外狀況處理常式可以與更高層級的例外狀況處理常式,不小心進行通訊,且此通訊可能會導致難以察覺的程式錯誤時,請務必小心。Use caution when developing your application because the consequence of a key conflict is that lower-level exception handlers can inadvertently communicate with higher-level exception handlers, and this communication might cause subtle program errors. 不過,如果您注意您可以使用索引鍵衝突來增強您的應用程式。However, if you are cautious you can use key conflicts to enhance your application.

避免索引鍵衝突Avoiding Key Conflicts

採用以產生唯一的索引鍵的索引鍵/值配對的命名慣例,以避免索引鍵衝突。Avoid key conflicts by adopting a naming convention to generate unique keys for key/value pairs. 例如,命名慣例可能會產生包含句號分隔的名稱,您的應用程式的金鑰、 提供配對和唯一識別碼的補充資訊的方法。For example, a naming convention might yield a key that consists of the period-delimited name of your application, the method that provides supplementary information for the pair, and a unique identifier.

假設兩個應用程式,名為產品和供應商,各有名稱為 Sales 的方法。Suppose two applications, named Products and Suppliers, each has a method named Sales. 產品應用程式中的銷售方法會提供產品的識別碼 (存貨保持單元或 SKU)。The Sales method in the Products application provides the identification number (the stock keeping unit or SKU) of a product. 供應商應用程式中的銷售方法提供識別碼或供應商的 SID。The Sales method in the Suppliers application provides the identification number, or SID, of a supplier. 因此,此範例中的命名慣例,會產生 「 Products.Sales.SKU"和"Suppliers.Sales.SID"索引鍵。Consequently, the naming convention for this example yields the keys, "Products.Sales.SKU" and "Suppliers.Sales.SID".

利用金鑰衝突Exploiting Key Conflicts

使用一或多個特殊的按照預先安排的金鑰存在來控制處理,以利用索引鍵衝突。Exploit key conflicts by using the presence of one or more special, prearranged keys to control processing. 假設在一個案例中,在呼叫堆疊階層架構中最高的層級的例外狀況處理常式會攔截所有較低層級例外狀況處理常式所擲回的例外狀況。Suppose, in one scenario, the highest level exception handler in the call stack hierarchy catches all exceptions thrown by lower-level exception handlers. 高層級的例外狀況處理常式有特殊的索引鍵的索引鍵/值組格式中剩餘的索引鍵/值組IDictionary某種非標準的方式; 物件,否則為將剩餘的索引鍵/值組格式以一般方式。If a key/value pair with a special key exists, the high-level exception handler formats the remaining key/value pairs in the IDictionary object in some nonstandard way; otherwise, the remaining key/value pairs are formatted in some normal manner.

現在假設,在另一個案例中,每個階層的層級呼叫堆疊的例外狀況處理常式會攔截由下一個較低層級的例外狀況處理常式所擲回的例外狀況。Now suppose, in another scenario, the exception handler at each level of the call stack hierarchy catches the exception thrown by the next lower-level exception handler. 此外,每個例外狀況處理常式知道所傳回的集合Data屬性包含一組可存取的索引鍵/值組的按照預先安排的一組金鑰。In addition, each exception handler knows the collection returned by the Data property contains a set of key/value pairs that can be accessed with a prearranged set of keys.

每個例外狀況處理常式會使用按照預先安排的金鑰組,使用唯一的例外狀況處理常式的資訊來更新相對應的索引鍵/值組的值元件。Each exception handler uses the prearranged set of keys to update the value component of the corresponding key/value pair with information unique to that exception handler. 在更新程序完成之後,例外狀況處理常式會擲回下一個較高層級的例外狀況處理常式的例外狀況。After the update process is complete, the exception handler throws the exception to the next higher-level exception handler. 最後,最高的層級的例外狀況處理常式會存取的索引鍵/值組,並顯示所有較低層級的例外狀況處理常式的彙總的更新資訊。Finally, the highest level exception handler accesses the key/value pairs and displays the consolidated update information from all the lower-level exception handlers.

適用於

另請參閱