Error Handling

HTTP Errors

It is possible to build specific error pages for differing types of HTTP errors within your application. For example, if someone types a URL directly and the page doesn't exist in your application the usual result is a generic 404 error page. However, you may want the error pages to fit your corporate style. Likewise other errors such as Server Error (500) will need to be provided.

These pages are not built into the menu system of your application but they can be created from your master page. These error pages are configured in the application configuration file (web.config). The default is that the custom error handling code is commented out:

<!--
 The <customErrors> section enables configuration 
 of what to do if/when an unhandled error occurs 
 during the execution of a request. Specifically, 
 it enables developers to configure html error pages 
 to be displayed in place of a error stack trace.

 <customErrors mode="RemoteOnly"
               defaultRedirect="GenericErrorPage.htm">
   <error statusCode="403" redirect="NoAccess.htm" />
   <error statusCode="404" redirect="FileNotFound.htm" />
 </customErrors>
-->

An example of providing custom error pages using the web.config file is:

<customErrors mode="On" defaultRedirect="genericerror.aspx">
  <error statusCode="404" redirect="404error.aspx"/>
</customErrors>

You can download a ZIP version of the HTTPErrors application.

Errors in your application

Up until the previous section we have had to write very little script code. The code that was required was fairly straightforward and had no (obvious) potential for error. Any sources of user error have been trapped using validation controls. However, the previous section has more script code and there are potential actions which may cause the application to fail. C# - like other languages - has a well defined mechanism for catching errors and responding in a graceful way. The basic mechanism is the try … catch statement.

try ... catch

The syntax for the try ... catch statement is:

    try
    {
        //code which may cause an error
    }
    catch
    {
        //code to be executed if an error occurs
    }

Any error prone code section is surrounded by the try section of the statement.

When an error occurs, instead of resulting in an obscure error page, with no link to the application, the statements in the catch section are executed. Typically, this section will cause an error message to be displayed in the page, and any loose ends to be tied up.

Web application SimpleError demonstrates this. A web form with three text boxes and a button has code which will convert the values in the first two text boxes to integers, add them up and display the result in the third text box. The basic code will only work correctly if the user has typed in two valid numbers within the range of a 32bit integer (around plus or minus 2,000,000,000). Any other combinations will cause an exception to be thrown.

   int A = Convert.ToInt32(TextBox1.Text);
   int B = Convert.ToInt32(TextBox2.Text);
   int C = A + B;
   TextBox3.Text = Convert.ToString(C);

Web application SimpleCatchError shows how errors can be trapped and responded to in a graceful way. Download a ZIP version of SimpleCatchError.

   try
   {
       int A = Convert.ToInt32(TextBox1.Text);
       int B = Convert.ToInt32(TextBox2.Text);
       int C = A + B;
       TextBox3.Text = Convert.ToString(C);
   }
   catch
   {
       TextBox3.Text = "Error in data";
   }

Sometimes we need more information about the error. C# makes this possible by allowing us to qualify the catch section with an error variable. We can use the information which was passed into the error variable when the error occurred and display it as part of our error display. The simplest method is to use a generic error variable of type System.Exception. The code, from web application SimpleTypeError, looks like this:

   try
   {
      int A = Convert.ToInt32(TextBox1.Text);
      int B = Convert.ToInt32(TextBox2.Text);
      int C = A + B;
      TextBox3.Text = Convert.ToString(C);
   }
   Catch (Exception err)
   {
      TextBox3.Text =
              err.GetType().ToString() + ": " + err.Message;
   }

You can download a ZIP version of SimpleTypeError.

If we know the types of error which we are expecting we can specify the error type. We can use multiple catch sections too to catch different kinds of error. The simple rule is to start with the most specific error and end up with the general error to mop up any leftover errors. Web application MultipleTypeError shows how this can be achieved. The code is shown below:

   txtError.Text = "";
   try
   {
       int A = Convert.ToInt32(TextBox1.Text);
       int B = Convert.ToInt32(TextBox2.Text);
       int C = A + B;
       TextBox3.Text = Convert.ToString(C);
   }
   catch (OverflowException err)
   {
       txtError.Text = "Number not in range!";
   }
   catch (FormatException err)
   {
       txtError.Text = "Missing number or invalid number typed";
   }
   Catch (Exception err)
   {
       txtError.Text = "Unknown error occurred!";
   }

Download a ZIP version of MultipleTypeError.

try ... catch ... finally

Sometimes an error occurs and you may want to treat the handling of the error separately from the mopping up operation.

For example, a database application may open a connection to the database. If an error occurs the error needs to be handled, but, error or not, the database connection will need to be closed. An extension of the try … catch statement allows this scenario to be accommodated. A finally clause will be executed whether or not there is an error. The code structure is shown below:

    // Code here allocates and uses resources
    try
    {
       // this code may generate an error
    }
    catch
    {
       // this code responds to the error
    }
    finally
    {
       // this code gets executed error or no error, so it can
       // release any resources from before the try clause.
    }
Valid XHTML 1.0! | Valid CSS! | WCAG Approved AA
Page design by: John P Scott - Hosting with: Netcetera