CHAPTER 7 UNDERSTANDING STRUCTURED EXCEPTION HANDLING
static void Main(string[] args)
{
...
// TargetSite actually returns a MethodBase object.
catch(Exception e)
{
Console.WriteLine("\n*** Error! ***");
Console.WriteLine("Member name: {0}", e.TargetSite);
Console.WriteLine("Class defining member: {0}",
e.TargetSite.DeclaringType);
Console.WriteLine("Member type: {0}", e.TargetSite.MemberType);
Console.WriteLine("Message: {0}", e.Message);
Console.WriteLine("Source: {0}", e.Source);
}
Console.WriteLine("\n***** Out of exception logic *****");
Console.ReadLine();
}
This time, you make use of the MethodBase.DeclaringType property to determine the fully qualified
name of the class that threw the error (SimpleException.Car, in this case) as well as the MemberType
property of the MethodBase object to identify the type of member (such as a property vs. a method) where
this exception originated. In this case, the catch logic would display the following:
*** Error! ***
Member name: Void Accelerate(Int32)
Class defining member: SimpleException.Car
Member type: Method
Message: Zippy has overheated!
Source: SimpleException
The StackTrace Property
The System.Exception.StackTrace property allows you to identify the series of calls that resulted in the
exception. Be aware that you never set the value of StackTrace, as it is established automatically at the
time the exception is created. To illustrate, assume you have once again updated your catch logic:
catch(Exception e)
{
...
Console.WriteLine("Stack: {0}", e.StackTrace);
}
If you were to run the program, you would find the following stack trace is printed to the console
(your line numbers and file paths may differ, of course):
Stack: at SimpleException.Car.Accelerate(Int32 delta)
in c:\MyApps\SimpleException\car.cs:line 65 at SimpleException.Program.Main()
in c:\MyApps\SimpleException\Program.cs:line 21
262