CHAPTER 7
Understanding Structured
Exception Handling
In this chapter, you will learn how to handle runtime anomalies in your C# code through the use of
structured exception handling (often cryptically abbreviated as SEH). Not only will you examine the C#
keywords that allow you to handle such matters (try, catch, throw, finally), you will also come to
understand the distinction between application-level and system-level exceptions, as well as the role of
the System.Exception base class. This discussion will lead into the topic of building custom exceptions
and, finally, to a quick look at the exception-centric debugging tools of Visual Studio.
Ode to Errors, Bugs, and Exceptions
Despite what our (sometimes inflated) egos may tell us, no programmer is perfect. Writing software is a
complex undertaking, and given this complexity, it is quite common for even the best software to ship
with various “problems.” Sometimes the problem is caused by “bad code” (such as overflowing the
bounds of an array). Other times, a problem is caused by bogus user input that has not been accounted
for in the application’s code base (e.g., a phone number input field assigned to the value “Chucky”).
Now, regardless of the cause of the problem, the end result is that the application does not work as
expected. To help frame the upcoming discussion of structured exception handling, allow me to provide
definitions for three commonly used anomaly-centric terms:
•
Bugs: These are, simply put, errors made by the programmer. For example,
suppose you are programming with unmanaged C++. If you fail to delete
dynamically allocated memory, resulting in a memory leak, you have a bug.
•
User errors: User errors, on the other hand, are typically caused by the individual
running your application, rather than by those who created it. For example, an
end user who enters a malformed string into a text box could very well generate an
error if you fail to handle this faulty input in your code base.
•
Exceptions: Exceptions are typically regarded as runtime anomalies that are
difficult, if not impossible, to account for while programming your application.
Possible exceptions include attempting to connect to a database that no longer
exists, opening a corrupted XML file, or trying to contact a machine that is
currently offline. In each of these cases, the programmer (or end user) has little
control over these “exceptional” circumstances.
253