CHAPTER 7 UNDERSTANDING STRUCTURED EXCEPTION HANDLING
The Data Property
The Data property of System.Exception allows you to fill an exception object with relevant auxiliary
information (such as a time stamp). The Data property returns an object implementing an interface
named IDictionary, defined in the System.Collections namespace. Chapter 8 examines the role of
interface-based programming, as well as the System.Collections namespace. For the time being, just
understand that dictionary collections allow you to create a set of values that are retrieved using a
specific key. Observe the next update to the Car.Accelerate() method:
public void Accelerate(int delta)
{
if (carIsDead)
Console.WriteLine("{0} is out of order...", PetName);
else
{
CurrentSpeed += delta;
if (CurrentSpeed >= MaxSpeed)
{
carIsDead = true;
CurrentSpeed = 0;
// We need to call the HelpLink property, thus we need
// to create a local variable before throwing the Exception object.
Exception ex =
new Exception(string.Format("{0} has overheated!", PetName));
ex.HelpLink = "http://www.CarsRUs.com";
// Stuff in custom data regarding the error.
ex.Data.Add("TimeStamp",
string.Format("The car exploded at {0}", DateTime.Now));
ex.Data.Add("Cause", "You have a lead foot.");
throw ex;
}
}
}
else
Console.WriteLine("=> CurrentSpeed = {0}", CurrentSpeed);
To successfully enumerate over the key/value pairs, you must first make sure to specify a using
directive for the System.Collections namespace, since you will use a DictionaryEntry type in the file
containing the class implementing your Main() method:
using System.Collections;
Next, you need to update the catch logic to test that the value returned from the Data property is not
null (the default value). After that, you make use of the Key and Value properties of the DictionaryEntry
type to print the custom data to the console:
catch (Exception e)
{
...
// By default, the data field is empty, so check for null.
Console.WriteLine("\n-> Custom Data:");
264