Free mag vol1 | Page 316

CHAPTER 7  UNDERSTANDING STRUCTURED EXCEPTION HANDLING Given these definitions, it should be clear that .NET structured exception handling is a technique for dealing with runtime exceptions. However, even for the bugs and user errors that have escaped your view, the CLR will often generate a corresponding exception that identifies the problem at hand. The .NET base class libraries define numerous exceptions, such as FormatException, IndexOutOfRangeException, FileNotFoundException, ArgumentOutOfRangeException, and so forth. Within the .NET nomenclature, an “exception” accounts for bugs, bogus user input, and runtime errors, even though we programmers may view each of these as a distinct issue. However, before we get too far ahead of ourselves, let’s formalize the role of structured exception handling and check out how it differs from traditional error-handling techniques.  Note To make the code examples used in this book as clean as possible, I will not catch every possible exception that may be thrown by a given method in the base class libraries. In your production-level projects, you should, of course, make liberal use of the techniques presented in this chapter. The Role of .NET Exception Handling Prior to .NET, error handling under the Windows operating system was a confused mishmash of techniques. Many programmers rolled their own error-handling logic within the context of a given application. For example, a development team could define a set of numerical constants that represented known error conditions, and make use of them as method return values. By way of an example, consider the following partial C code: /* A very C-style error trapping mechanism. */ #define E_FILENOTFOUND 1000 int UseFileSystem() { // Assume something happens in this function // that causes the following return value. return E_FILENOTFOUND; } void main() { int retVal = UseFileSystem(); if(retVal == E_FILENOTFOUND) printf("Cannot find file..."); } This approach is less than ideal, given the fact that the constant E_FILENOTFOUND is little more than a numerical value, and is far from being a helpful agent regarding how to deal with the problem. Ideally, you would like to wrap the error’s name, a descriptive message, and other helpful information about this error condition into a single, well-defined package (which is exactly what happens under structured exception handling). In addition to a developer’s ad hoc techniques, the Windows API defines hundreds of error codes that come by way of #defines, HRESULTs, and far too many variations on the simple Boolean (bool, BOOL, VARIANT_BOOL, and so on). Furthermore, many C++ COM developers made use of a small set of standard 254