7.11. 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 specifying 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 exception can be thrown and caught, and more data can be added in subsequent catchblocks 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"))
e.Data["Cause"]="Fixed computer"
throw;
}
}
catch (Exception e)
{
e.Data["Comment"]="Always grumpy you are";
throw;
}
}
catch (Exception e)
{
e.Data["Reassurance"]="Error Handled";
throw;
}
}The final catch block can then iterate over the Exception.Data collection and display all of the supporting data that has been gathered in the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access