Home

ASP.NET With Visual Basic Exception Handling: .NET Support for Exception Handling

 

Exceptions in the .NET Framework

 

The Exception Class

The .NET Framework provides a good level of support for exception handling that you can use for your web pages. To support exception handling, the .NET Framework provides the Exception class. Once the compiler encounters an error, the Exception class allows you to identify the type of error and take appropriate action(s).

Normally, Exception mostly serves as the general class of exceptions. Anticipating various types of problems that can occur in a program, Microsoft derived various classes from Exception to make this issue friendlier. As a result, almost any type of exception you may encounter already has a class created to deal with it. Therefore, when your program faces an exception, you can easily access the class appropriate for that error. There are so many exception classes that we cannot study or review them all. The solution we will use is to introduce or review a class when we meet its type of error.

The Exception's Message

In exception handling, errors are dealt with in the Catch section. On the right side of Catch, behave as if you were declaring a variable of the type of exception you want to deal with. By default, an exception is first of type Exception. Based on this, a typical formula to implement exception handling is:

Try
	' Process the normal flow of the program here
Catch Argument As Exception
	' Deal with the exception here
End Try

When an exception occurs in the Try section, code compilation is transferred to the Catch section. If you declare the exception as an Exception type, this class will identify the error. One of the properties of the Exception class is called Message. This property contains a string that describes the type of error that occurred. You can then use this Exception.Message property to display an error message if you want. Here is an example:

<%@ Page Language="VB" %>
<html>
<head>

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    Dim HourlySalary As Double, WeeklyTime As Double
    Dim WeeklySalary As Double

    Try
        HourlySalary = CDbl(txtHourlySalary.Text)
        WeeklyTime = CDbl(txtWeeklyTime.Text)

        WeeklySalary = HourlySalary * WeeklyTime

        txtWeeklySalary.Text = FormatNumber(WeeklySalary)
    Catch ex As Exception
        Response.Write(ex.Message)
    End Try
End Sub
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmPayrollCalculation" runat="server">
  <table>
    <tr>
      <td>Hourly Salary:</td>
      <td>
        <asp:TextBox ID="txtHourlySalary" runat="server"></asp:TextBox>
      </td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>Weeekly Salary:</td>
      <td><asp:TextBox ID="txtWeeklyTime" runat="server"></asp:TextBox></td>
      <td>
	<asp:Button ID="btnCalculate"
                    Text="Calculate"
                    OnClick="btnCalculateClick"
                    runat="server"></asp:Button></td>
    </tr>
    <tr>
      <td>Weeekly Salary:</td>
      <td><asp:TextBox ID="txtWeeklySalary" runat="server"></asp:TextBox></td>
      <td>&nbsp;</td>
    </tr>
  </table>
</form>

</body>
</html>

Here is an example of executing the web page:

Exception Handling

Custom Error Messages

As you can see, one of the strengths of the Exception.Message property is that it gives you a good indication of the type of problem that occurred. Sometimes, the message provided by the Exception class may not appear explicit enough. In fact, you may not want to show it to the user since, as in this case, the user may not understand what the word "Cast" in this context means and why it is being used. As an alternative, you can create your own message and display it to the user. Here is an example:

<%@ Page Language="VB" %>
<html>
<head>

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    Dim HourlySalary As Double, WeeklyTime As Double
    Dim WeeklySalary As Double

    Try
        HourlySalary = CDbl(txtHourlySalary.Text)
        WeeklyTime = CDbl(txtWeeklyTime.Text)

        WeeklySalary = HourlySalary * WeeklyTime

        txtWeeklySalary.Text = FormatNumber(WeeklySalary)
    Catch ex As Exception
        Response.Write("The operation could not be carried because " & _
                       "the number you typed is not valid")
    End Try
End Sub
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmPayrollCalculation" runat="server">
  <table>
    <tr>
      <td>Hourly Salary:</td>
      <td>
        <asp:TextBox ID="txtHourlySalary" runat="server"></asp:TextBox>
      </td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>Weeekly Salary:</td>
      <td><asp:TextBox ID="txtWeeklyTime" runat="server"></asp:TextBox></td>
      <td>
	<asp:Button ID="btnCalculate"
                    Text="Calculate"
                    OnClick="btnCalculateClick"
                    runat="server"></asp:Button></td>
    </tr>
    <tr>
      <td>Weeekly Salary:</td>
      <td><asp:TextBox ID="txtWeeklySalary" runat="server"></asp:TextBox></td>
      <td>&nbsp;</td>
    </tr>
  </table>
</form>

</body>
</html>

Here is an example of executing the web page:

Exception Handling

You can also combine the Exception.Message message and your own message:

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    Dim HourlySalary As Double, WeeklyTime As Double
    Dim WeeklySalary As Double

    Try
        HourlySalary = CDbl(txtHourlySalary.Text)
        WeeklyTime = CDbl(txtWeeklyTime.Text)

        WeeklySalary = HourlySalary * WeeklyTime

        txtWeeklySalary.Text = FormatNumber(WeeklySalary)
    Catch ex As Exception
        Response.Write(ex.Message & vbCrLf & _
                       "The operation could not be carried because " & _
                       "the number you typed is not valid")
    End Try
End Sub
</script>

Here is an example of executing the web page:

Exception Handling

A Review of .NET Exception Classes

 

Introduction

The .NET Framework provides various classes to handle almost any type of exception you can think of. There are so many of these classes that we can only mention the few that we regularly use in our application.

There are two main ways you can use one of the classes of the .NET Framework. If you know for sure that a particular exception will be produced, pass its name to the Catch clause and display a custom message. The second option you have consists of using the throw keyword. We will study it later.

From now on, we will try to always indicate the type of exception that could be thrown if something goes wrong in a program

InvalidCastException

When studying data formatting in Lesson 5, we saw that everything the user types into an application using the keyboard is primarily a string and that you must convert it to the appropriate type before using it. When you request a specific type of value from the user, after the user has typed it and you decide to convert it to the appropriate type using one of the built-in conversion functions (CDbl(), CInt, CDate, CSng, CDec, etc), if your conversion fails, the program produces (in the next lessons, we will use he word "throw") an error. The error is from the InvalidCastException class.

The OverflowException Exception

A computer application receives, processes, and produces values on a regular basis as the program is running. To better manage these values, the compiler uses appropriate amounts of space to store its values. It is not unusual that either you the programmer or a visitor of your web page provide a value that is beyond the allowed range of the data type. For example, a byte uses 8 bits to store a value and a combination of 8 bits can store a number no more than 255. If you provide a value higher than 255 to be stored in a byte, you get an error.

When a value beyond the allowable range is asked to be stored in memory, the compiler produces (or "throws") an error of the OverflowException class. As with the other errors, when this exception is thrown, you should take appropriate action.

FormatException

Once again, when studying the techniques of converting or formatting values in Lesson 5, we saw that a value is passed to a conversion function for analysis. For a primitive data type, the conversion function scans the string and if the string cannot be converted into a valid character or number, the compiler usually throws an InvalidCastException exception as we saw above. Other data types such as Date also use use this technique to scan the value submitted to it. For example, if you request a date value from the user, the CDate() function scans the string to validate it. In US English, CDate() expects the user to type a string in the form m/d/yy or mm/dd/yy or mm/dd/yyyy or yyyy/mm/dd. One way you can avoid this is to guide the user about the type of expected value. You should still prepare to take appropriate actions, just in case this error is thrown.

The DivideByZeroException Exception

Division by zero is an operation to always avoid. It is so important that it is one of the most fundamental exceptions of the computer. It is addressed at the core level even by the Intel and AMD processors. It is also addressed by the operating systems at their level. It is also addressed by most, if not all, compilers. It is also addressed by most, if not, all libraries. This means that this exception is never welcomed anywhere. The .NET Framework also provides it own class to face this operation.

If an attempt to divide a value by 0, the compiler throws a DivideByZeroException exception. We will see an example later.

 
 
 

Techniques of Using Exceptions

 

Throwing an Exception

As mentioned above, the Exception class is equipped with a Message property that carries a message for the error that occurred. We also mentioned that the message of this property may not be particularly useful to a user. Fortunately, you can create your own message and pass it to the Exception. To be able to receive custom messages, the Exception class provides the following constructor:

public Exception(string message)

To use it, in the section that you are anticipating the error, type the throw keyword followed by a new instance of the Exception class using the constructor that takes a string.

Catching Various Exceptions

In the examples above, when we anticipated some type of problem, we instructed the compiler to use our default Catch section. We left it up to the compiler to find out when there was a problem and we provided a Catch section to deal with it. A method with numerous or complex operations and requests can also produce different types of errors. With such a type of program, you should be able to face different problems and deal with them individually, each by its own kind. To do this, you can create different Catch sections, each made for a particular error. The formula used would be:

Try
	' Code to Try
Catch One Type of Exception
	' One Exception
Catch Another Type Of Exception
	' Another Exception
End Try

The compiler would proceed in a top-down:

  1. Following the normal flow of the program, the compiler enters the Try block
  2. If no exception occurs in the Try block, the rest of the Try block is executed
    If an exception occurs in the Try block, the compiler registers the type of error that occurred. If there is a throw line, the compiler registers it also:
    1. The compiler gets out of the Try section
    2. The compiler examines the first Catch. If the first Catch matches the thrown error, that catch executes and the exception handling routine may seize. If the first Catch doesn’t match the thrown error, the compiler proceeds with the next Catch
    3. The compiler checks the next match, if any and proceeds as in the first match. This continues until the compiler finds a Catch that matches the thrown error
    4. If one of the catches matches the thrown error, its body executes. If no Catch matches the thrown error, the compiler calls the Exception class and uses the default message

Multiple catches are written if or when a try block is expected to throw different types of errors.

This program works fine as long as the user types a valid sequence of values made of a number, a valid arithmetic operator, and a number. Anything else, such an invalid number, an unexpected operator, or a wrong sequence (such as a number then another number instead of an operator), would cause an error to be thrown. Obviously various bad things could happen when this program is running. To handle the exceptions that this program could produce, you can start with the most likely problem that would occur. Trusting that a user is able to provide the two numbers that are requested, it is possible that a user would type an invalid operator. For example, for this program we will perform only the addition (+), the subtraction(-), the multiplication(*), and the division(/). Therefore, we will first validate the operator.

Exceptions Nesting

The calculator simulator we have studied so far performs a division as one of its assignments. We learned that, in order to perform any operation, the compiler must first make sure that the user has entered a valid operator. Provided the operator is one of those we are expecting, we also must make sure that the user typed valid numbers. Even if these two criteria are met, it was possible that the user enter 0 for the denominator. The block that is used to check for a non-zero denominator depends on the exception that validates the operators.

You can create an exception inside of another. This is referred to as nesting an exception. This is done by applying the same techniques we used to nest conditional statements. This means that you can write an exception that depends on, and is subject to, another exception. To nest an exception, write a Try block in the body of the parent exception. The nested Try block must be followed by its own Catch(es) clause. To effectively handle the exception, make sure you include an appropriate Throw in the Try block.

 
 
   
 

Home Copyright © 2009-2013 FunctionX, Inc., Inc.