Structured Exception Handling

One of the greatest enhancements introduced with ASP.NET is structured exception handling. With structured exception handling, you can be more selective with error trapping. Rather than put a blanket On Error Resume Next statement in your code and constantly check for errors in the Err object, you can enclose blocks of code that are prone to errors and catch specific exceptions.

When to Use Structured Exception Handling

Structured exception handling can be an effective tool for catching and dealing with runtime errors. However, it should be used only when you are going to do something useful with the exception that is raised. For example, if you need to do any cleanup processing when an exception occurs, then structured exception handling is ideal. If you want to log the error and display it to the user, then you can implement a global exception handler with a custom error page (discussed later in this chapter in the section “Implementing the Application_Error Event Handler”).

Effective Use of Structured Exception Handling

When using structured exception handling in ASP.NET, avoid using the generic Exception class. If you want to trap and clean up after a particular type of exception, then specify it. Later, we’ll discuss using a global exception handler and a custom error page to catch generic exceptions. Listings 4.24 and 4.25 demonstrate catching specific exceptions.

Listing 4.24. Trapping a Specific Exception Type
<%@ Page Language="C#" %> 
<%@ Import Namespace="System.IO" %> 

<% 
try 
{
     StreamReader sr = new StreamReader(@"c:ogusfile.txt"); 
} 
catch(FileNotFoundException e) 
{
     Response.Write(e. ToString()); 
} 
%> 

Listing 4.25. Trapping a Specific Exception Type (Visual Basic .NET)
<%@ Page Language="VB" %> 
<%@ Import Namespace="System.IO" %> 

<% 
Try 
     Dim sr As StreamReader = New StreamReader("c:ogusfile.txt") 
Catch e As FileNotFoundException 
     Response.Write(e. ToString()) 
End Try 
%> 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset