
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
422
|
Chapter 7: Exception Handling
For information about wiring up top-level exception handlers in your application,
see Recipes 7.10 and 7.20.
7.18 Giving Exceptions the Extra Info They Need
with Exception.Data
Problem
You want to send some additional information along with an exception.
Solution
Use the Data property on the System.Exception object to store key-value pairs of
information relevant to the exception.
For example, say there is a
System.ArgumentException being thrown from a section of
code and you want to include the underlying cause and the length of time it took.
The code would add two key-value pairs to the
Exception.Data property by specify-
ing the key in the indexer and then assigning the value.
In the example that follows, the
Data for the irritable exception uses "Cause" and
"Length" for its keys. Once the items have been set in the Data collection, the excep-
tion can be thrown and caught, and more data can be added in subsequent
catch
blocks for as many levels of exception handling as the exception is allowed to
traverse.
try
{
try
{
try
{
try
{
ArgumentException irritable =
new ArgumentException("I'm irritable!");
irritable.Data["Cause"]="Computer crashed";
irritable.Data["Length"]=10;
throw irritable;
}
catch (Exception e)
{
// See if I can help...
if(e.Data.Contains("Cause")) ...