Chapter 9: Exception Handling

Chapter 9: Exception Handling


Exception handling is an important ingredient of a robust application and should be included in the application design of every .NET program. Exception handling helps applications identify and respond to exceptional events in a known and robust manner. This enhances the correctness of an application, which naturally improves customer satisfaction. Unfortunately, exception handling is often an afterthought, which leads to poorly implemented solutions for exception handling and a less robust application. Starting with application design, exception handling should be included in all aspects of application planning and development.

What is an exception? Exceptions are exceptional events or error conditions within an application and are categorized as system or application exceptions. System exceptions are raised by the Common Language Runtime (CLR) and include null reference, out of memory, divide by zero, and stack overflow exceptions. Application exceptions, considered custom exceptions, are thrown by the application, not by the CLR. Some exceptional events or error conditions are detectable by application logic, not by the runtime. Application exceptions are useful in those circumstances. As an example, constructors that fail are not always detectable by the CLR. In addition, constructors implicitly return void, which prevents returning an error code. For these reasons, throwing an application exception in the failed constructor is the best solution.

Exceptions should be used only for exceptions. Exception handling is not a substitute for transfer of control or a goto statement. Exceptions are expensive when compared with conventional transfer of control. Whenever possible, applications should preempt exceptions and avoid the accompanying costs. Performing data validation, where incorrect values can cause exceptions, is one measure that prevents exceptions. Data validation and, if necessary, returning an error code is undoubtedly cheaper than raising an exception.

The overuse of exceptions makes code harder to read and maintain. Errors that frequently occur should not be handled with exception handling, but with error codes or returns. Remember, exceptions should be reserved for exceptional events.