CHAPTER 7 UNDERSTANDING STRUCTURED EXCEPTION HANDLING
The string returned from StackTrace documents the sequence of calls that resulted in the throwing
of this exception. Notice how the bottommost line number of this string identifies the first call in the
sequence, while the topmost line number identifies the exact location of the offending member. Clearly,
this information can be quite helpful during the debugging or logging of a given application, as you are
able to “follow the flow” of the error’s origin.
The HelpLink Property
While the TargetSite and StackTrace properties allow programmers to gain an understanding of a
given exception, this information is of little use to the end user. As you have already seen, the
System.Exception.Message property can be used to obtain human-readable information that can be
displayed to the current user. In addition, the HelpLink property can be set to point the user to a specific
URL or standard Windows help file that contains more detailed information.
By default, the value managed by the HelpLink property is an empty string. If you want to fill this
property with a more interesting value, you need to do so before throwing the System.Exception object.
Here are the relevant updates 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";
throw ex;
}
else
Console.WriteLine("=> CurrentSpeed = {0}", CurrentSpeed);
}
}
The catch logic could now be updated to print out this help link information as follows:
catch(Exception e)
{
...
Console.WriteLine("Help Link: {0}", e.HelpLink);
}
263