CHAPTER 7 UNDERSTANDING STRUCTURED EXCEPTION HANDLING
In essence, a try block is a section of statements that may throw an exception during execution. If
an exception is detected, the flow of program execution is sent to the appropriate catch block. On the
other hand, if the code within a try block does not trigger an exception, the catch block is skipped
entirely, and all is right with the world. The following output shows a test run of this program.
***** Simple Exception Example *****
=> Creating a car and stepping on it!
Jamming...
=> CurrentSpeed = 30
=> CurrentSpeed = 40
=> CurrentSpeed = 50
=> CurrentSpeed = 60
=> CurrentSpeed = 70
=> CurrentSpeed = 80
=> CurrentSpeed = 90
*** Error! ***
Method: Void Accelerate(Int32)
Message: Zippy has overheated!
Source: SimpleException
***** Out of exception logic *****
As you can see, after an exception has been handled, the application is free to continue on from the
point after the catch block. In some circumstances, a given exception could be critical enough to warrant
the termination of the application. However, in a good number of cases, the logic within the exception
handler will ensure the application can continue on its merry way (although it could be slightly less
functional, such as not being able to connect to a remote data source).
Configuring the State of an Exception
Currently, the System.Exception object configured within the Accelerate() method simply establishes a
value exposed to the Message property (via a constructor parameter). As shown previously in Table 7-1,
however, the Exception class also supplies a number of additional members (TargetSite, StackTrace,
HelpLink, and Data) that can be useful in further qualifying the nature of the problem. To spruce up our
current example, let’s examine further details of these members on a case-by-case basis.
The TargetSite Property
The System.Exception.TargetSite property allows you to determine various details about the method
that threw a given exception. As shown in the previous Main() method, printing the value of TargetSite
will display the return type, name, and parameter types of the method that threw the exception.
However, TargetSite does not return just a vanilla-flavored string, but rather a strongly typed
System.Reflection.MethodBase object. This type can be used to gather numerous details regarding the
offending method, as well as the class that defines the offending method. To illustrate, assume the
previous catch logic has been updated as follows:
261