Saturday 26 November 2011

Exception Handling

Error handling is very important for any serious application. It is very crucial that the application is capable of detecting the errors and take corrective measures to the maximum possible extend. If the error situation is beyond the control of the application, it should report the situation to the user/administrator so that an external action can be taken.
The following are the most common ways of handling exceptions in an ASP.NET web application.
  1. Structured Exception Handling
  2. Error Events
  3. Custom Error Pages
Structured Exception Handling
The most popular error handling is Structured Exception Handling (SEH). Most of us are familiar with it in the form of try..catch blocks. All of us use SEH a lot in whatever application that we are working on. The primary focus of SEH is to make sure that a block of code is executed correctly, and if an exception takes place, we have another piece of code which can take care of the exception and take some corrective measures if possible.
SEH is used to protect the application from an exceptional situation where something unexpected happens. For example the application tries to connect to a database server and the server is not available. It is an exceptional situation or an exception :-). If such a case happens the developer can handle the situation in the catch block and take the necessary action. I have seen smart developers making use of SEH for the application logic too. for example, assume that the developer needs to open a file and display the content. Ideally he needs to check if the file exists first and then if it exists open it as follows. (This kind of programming is called DEFENSIVE Programming).
1.If file exists    
2.    work with the file 
3.else    
4.   take action 
5.end if
But the developer can simply use a try..catch block to open the file without even checking if the file exists as 1.try    
2.     just work with the file 
3.catch 
4.     file-does-not-exist-exception    
5.     take action 
6.end try
The above approach reduces the complexity of checking for the existing of the file etc. However it adds some overhead to the system. Generating and handling an exception takes some system resources. I have also seen people using SEH to branch the code execution to a specific upper function block, from inside a series of complex nested functions.
For example function a calls b and b calls c and c calls d and d calls e and if the developer wants to transfer control to a specific location in any of the parent methods, he or she can make use of SEH. SEH is mostly used for procedure/function level error handling. Any code which access external resources like database connections, files/folders, URLs should always be inside try..catch blocks because they are most vulnerable for exceptions.
I have experienced a lot of trouble with combo boxes too and hence would recommend that any action that you do on a combo box should be inside try/catch blocks. Another area where you might consider is working with a dataaset where a null value can cause an exception.
Error Events
Most of the times we will be able to put the code into try..catch blocks. But exceptions occurs in exceptional situations. There might be several cases when we would not be able to fore-see that a given block code is vulnerable to a specific exception.
For example,
1.dim CustomerName as string = new string("jacob")
The above statement is not a candidate for an error. No one would expect that the above statement can generate an error. But what if the system memory is full? The system is not able to allocate memory for that variable and it will throw an exception. Is it practical to put every line of code in try..catch blocks and catch every possible exception with every line of code? Of course not.
The best idea is to use Error Events of ASP.NET to handle such exceptions. Error events can be used to catch exceptions which are not handled with SEH. Asp.net provides three events to handle error conditions.
  1. a. page_error
  2. b. global_error
  3. c. application_error
You can write excpetion handling code in page_error to handle any un-handled exceptions that occur inside your page. similarly global_error and application_error can be used for application-wide error handling. From within the error event (page_error, global_error or application_error) you need to find the exception which occured. Server.GetLastError() can be used to retrieve the exception which triggered the error. After you have processed the error, you should call Server.ClearError() so that the further exception processing/handlers are not called.
Custom Error Pages
Yet another way you can handle errors in ASP.NET Web applications is by using Custom Error pages. When an exception occurs you can redirect the user to a customized page which explains the error condition or just give a friendly note to the user. The scope of Custom error page is very much large that it can even detect errors which are not related to the web application. For example, if your web application is down, still you can instruct IIS to show the user a specific page.
Custom error pages can be configured in 3 different ways.
  1. 1. Configure the custom error page with IIS
  2. 2. Configure the custom error page with web.config
  3. 3. Configure the custom error page declaratively in each web form
 Configuring a custom error page with IIS

You can configure a custom error page with IIS by opening the properties window of your application.  Custom error pages in IIS work based on HTTP response codes. you can define a custom page for each HTTP error that you need to handle. The question "which error code should I handle" largely depends on your application. However, I think the following HTTP response codes may be handled in a normal web application. HTTP 401 - Unauthorized HTTP 404 - Page Not Found HTTP 408 - Request Timeout HTTP 500 - Internal Server Error HTTP 503 - Server Not Available
Configuring Custom Error Pages in Web.Config
The section if web.config can be used to configure error pages. The following example shows a typical example.
1.<customerrors defaultredirect="Error.aspx" mode="on">    
2.     <error redirect="PageNotFound.aspx" statuscode="404" />    
3.     <error redirect="InternalServerErr.aspx" statuscode="500" /> 
4.</customerrors>
Note: Custom error handling using web.config is applicable to ASP.NET resources only. For example, if a "page not found" error occurs with an aspx file, your custom error page will be displayed. However if a "page not found" error occurs for an html file, your application's error handler page will not be launched. To handle situations external to the web application, the setting needs to be configured with IIS.
Page Level Error Configuration
The error configuration on web.config has application wide scope. However, it is possible to configure the error pages for a given web form. You can specify error pages declaratively on your web form as shown in the following example.
1.<%@ page 
2.    language="vb" 
3.    AutoEventWireup="false" 
4.    codebehind="pagename.aspx.vb" 
5.    inherits="projectname.pagename" 
6.    errorPage="Error.aspx" %>
Setting on the web page supersedes the configuration setting on the web.config. In the above example, if an error occurs inside the above page (pagename.aspx) the user will be taken to "error.aspx" which might contain the details of the page. You can use Server.GetLastError() to identify the exception and can display an appropriate message to the user.

2 comments: