Chapter 7. Error Handling

Introduction

Journeyman programmers know that proper error handling is critical to the operation of an application. Without it, your chances of making the application truly fault tolerant are less than remote. Taking the time to plan an error-handling strategy in the early stages of a project can pay off handsomely as the project progresses. Yet, too often error handling is given short shrift, for want of time, interest, awareness, accessibility, or who knows what.

Fortunately, error handling has been greatly improved in ASP.NET, making it much more approachable and much easier to implement than was the case for classic ASP. Taking a page or two from the Java playbook, ASP.NET now provides state of the art handling of errors with exceptions and error-handler events.

The error-handling model in ASP.NET lets you handle errors easily at the method, page, and application levels of your web applications. Most applications will use some combination of these to handle problems when they arise. In this chapter, we have included recipes for handling errors at each level:

Method level

When does it make sense to handle errors locally versus letting them propagate up to a higher level? In general, you want to handle recoverable errors in the method where they occur, and let nonrecoverable errors propagate up. Recipe 7.1 delves into this subject in some detail. It also helps you understand all the nuances of the Try...Catch...Finally block, and even includes sets of if...then ...

Get ASP.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.