CHAPTER 7 UNDERSTANDING STRUCTURED EXCEPTION HANDLING
COM interfaces (e.g., ISupportErrorInfo, IErrorInfo, ICreateErrorInfo) to return meaningful error
information to a COM client.
The obvious problem with these older techniques is the tremendous lack of symmetry. Each
approach is more or less tailored to a given technology, a given language, and perhaps even a given
project. To put an end to this madness, the .NET platform provides a standard technique to send and
trap runtime errors: structured exception handling (SEH).
The beauty of this approach is that developers now have a unified approach to error handling,
which is common to all languages targeting the .NET platform. Therefore, the way in which a C#
programmer handles errors is syntactically similar to that of a VB programmer, or a C++ programmer
using C++/CLI.
As an added bonus, the syntax used to throw and catch exceptions across assemblies and machine
boundaries is identical. For example, if you use C# to build a Windows Communication Foundation
(WCF) service, you can throw a SOAP fault to a remote caller, using the same keywords that allow you to
throw an exception between methods in the same application.
Another bonus of .NET exceptions is that rather than receiving a cryptic numerical value that simply
identifies the problem at hand, exceptions are objects that contain a human-readable description of the
problem, as well as a detailed snapshot of the call stack that triggered the exception in the first place.
Furthermore, you are able to give the end user help-link information that points the user to a URL that
provides details about the error, as well as custom programmer-defined data.
The Building Blocks of .NET Exception Handling
Programming with structured exception handling involves the use of four interrelated entities:
•
A class type that represents the details of the exception
•
A member that throws an instance of the exception class to the caller under the
correct circumstances
•
A block of code on the caller’s side that invokes the exception-prone member
•
A block of code on the caller’s side that will process (or catch) the exception,
should it occur
The C# programming language offers four keywords (try, catch, throw, and finally) that allow you
to throw and handle exceptions. The object that represents the problem at hand is a class extending
System.Exception (or a descendent thereof). Given this fact, let’s check out the role of this exceptioncentric base class.
The System.Exception Base Class
All exceptions ultimately derive from the System.Exception base class, which in turn derives from
System.Object. Here is the crux of this class (note that some of these members are virtual and may thus
be overridden by derived classes):
public class Exception : ISerializable, _Exception
{
// Public constructors
public Exception(string message, Exception innerException);
public Exception(string message);
public Exception();
...
255