Session 11 - Error Handling

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.
    }

Session 11 - Workshop

  1. Implement error handling in one of your workshop applications. You will need to analyse all situations where error conditions can arise. This will usually be when user interactions occur, but there may be other situations too.
Valid XHTML
1.0! | Valid CSS! | Bobby WorldWide Approved AAA