Home

Error Handling

 

Introduction to Errors

 

Overview

We always to create a problem-free application, one that always behaves as expected. In reality, many things can go wrong while a program is running. As an application developer, you can anticipate as many bad behaviors as possible so you can take appropriate actions. To assist you with dealing with errors, the Visual Basic language provides many keywords, operators, and techniques.

 

Introduction to Handling Errors

To deal with errors in your code, the Visual Basic language provides various techniques. One way you can do this is to prepare your code for errors. When an error occurs, you would present a message to the user to make him/her aware of the issue (the error).

To prepare a message, you can create a section of code in the procedure where the error would occur. To start that section, you create a label. Here is an example:

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

<title>Exercise</title>

</head>
<body>

<%

ThereWasAProblem:

%>

</body>
</html>

You can also do this inside a procedure (a sub procedure or a function). Here is an example:

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

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

ThereWasAProblem:
    
End Sub
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmPayroll" runat="server">
  <table>
    <tr>
      <td>Hourly Salary:</td>
      <td>
        <asp:TextBox ID="txtHourlySalary" 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>

Notice that the section starts with a label. After (under) the label, you can specify your message. You can formulate the message using Response.Write() or a message box. Here is an example:

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

ThereWasAProblem:
    Response.Write("An error occurred when the application executed")
    
End Sub
</script>

If you simply create a label and its message like this, its section would always execute. 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
    Dim WeeklySalary As Double

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * 40

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

ThereWasAProblem:
    Response.Write("An error occurred when the application executed")
    
End Sub
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmPayroll" runat="server">
  <table>
    <tr>
      <td>Hourly Salary:</td>
      <td>
        <asp:TextBox ID="txtHourlySalary" 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 code:

Error Handling

To avoid this, you should find a way to interrupt the flow of the program before the label section. One way you can do this is to add a line marked Exit Function or Exit Sub before the label. This would be done as follows:

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

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

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * 40

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

    Exit Sub

ThereWasAProblem:
    Response.Write("An error occurred when the application executed")
    
End Sub
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmPayroll" runat="server">
  <table>
    <tr>
      <td>Hourly Salary:</td>
      <td>
        <asp:TextBox ID="txtHourlySalary" 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 using the web page:

Error Handling

In Case of Error

 

Jump to a Label

We saw that you can create a label that would present a message to the user when a problem happens. Before an error occurs, you would indicate to the compiler where to go if an error occurs. To provide this information, under the line that starts the procedure, type an On Error GoTo expression followed by the name of the label where you created the message. Here is an example:

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

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    On Error GoTo ThereWasAProblem

    Dim HourlySalary As Double
    Dim WeeklySalary As Double

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * 40

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

    Exit Sub

ThereWasAProblem:
    Response.Write("An error occurred when the application executed")
    
End Sub
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmPayroll" runat="server">
  <table>
    <tr>
      <td>Hourly Salary:</td>
      <td>
        <asp:TextBox ID="txtHourlySalary" 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 running the code:

Error Handling

The On Error GoTo indicates to the compiler where to transfer code if an error occurs.

Go to a Numbered Label

Instead of defining a lettered label where to jump in case of error, you can create a numeric label:

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

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

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * 40

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

45:
    Response.Write("An error occurred when the application executed")
    
End Sub
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmPayroll" runat="server">
  <table>
    <tr>
      <td>Hourly Salary:</td>
      <td>
        <asp:TextBox ID="txtHourlySalary" 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>

After creating the numeric label, you can ask the compiler to jump to it if a problem occurs. To do this, type On Error GoTo followed by the numeric label. The compiler would still jump to it when appropriate. Here is an example:

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    On Error GoTo 45

    Dim HourlySalary As Double
    Dim WeeklySalary As Double

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * 40

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

    Exit Sub

45:
    Response.Write("An error occurred when the application executed")
    
End Sub
</script>

This version of the program would behave like the previous one and produce the same result.

Notice that the numeric label works like the lettered label. In other words, before writing the On Error GoTo expression, you must have created the label. In reality, this is not a rule. You can ask the compiler to let you deal with the error one way or another. To do this, use the On Error GoTo 0 or On Error GoTo -1 expression. Here is an example:

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    On Error GoTo 0

    Dim HourlySalary As Double
    Dim WeeklySalary As Double

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * 40

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)
End Sub
</script>

In this case, if/when the error occurs, you must have a way to deal with it.

Resume the Code Flow

In every code we have explored so far, we anticipated that there could be a problem and we dealt with it. In most cases, after dealing with the error, you must find a way to continue with a normal flow of your program. In some other cases, you may even want to ignore the error and proceed as if everything were normal, or you don't want to bother the user with some details of the error.

After programmatically dealing with an error, to resume with the normal flow of the program, you use the Resume operator. It presents many options.

After an error has occurred, to ask the compiler to proceed with the regular flow of the program, type the Resume keyword. Here is an example:

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    On Error GoTo ThereWasAProblem

    Dim HourlySalary As Double
    Dim WeeklySalary As Double

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)

    Resume

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * 40

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

    Exit Sub

ThereWasAProblem:
    Response.Write("An error occurred when the application executed")
    
End Sub
</script>

Notice that you can write the Resume operator almost anywhere. In reality, you should identify where the program would need to resume. If you want the program to continue with an alternate value than the one that caused the problem, in the label section, type Resume Next. Here is an example:

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    On Error GoTo ThereWasAProblem

    Dim HourlySalary As Double
    Dim WeeklySalary As Double

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * 40

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

    Exit Sub

ThereWasAProblem:
    Response.Write("An error occurred when the application executed")

    Resume Next
    
End Sub
</script>

We know that in our code, there was probably a problem, which is the reason we presented a message to the user. Then, when code resumes, where should the compiler go? After all, the problem was not solved. One way you can deal with the problem is to provide an alternative to what caused the problem, since you are  supposed to know what type of problem occurred. In the case of an arithmetic calculation, imagine we know that the problem was caused by the user typing an invalid number (such as typing a name where a number was expected). Instead of letting the program crash, we can provide an alternate number. The easiest number is 0.

Before asking the compiler to resume, to provide an alternative solution (a number in this case), you can re-initialize the variable that caused the error. Here is an example:

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    On Error GoTo ThereWasAProblem

    Dim HourlySalary As Double
    Dim WeeklySalary As Double

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * 40

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

    Exit Sub

ThereWasAProblem:
    Response.Write("An error occurred when the application executed")
    HourlySalary = 0

    Resume Next
    
End Sub
</script>

If there are many variables involved, as is the case for us, you can initialize each. Here an example:

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

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    On Error GoTo ThereWasAProblem

    Dim HourlySalary As Double, WeeklyTime As Double
    Dim WeeklySalary As Double

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)
    WeeklyTime = CDbl(txtWeeklyTime.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * WeeklyTime

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

    Exit Sub

ThereWasAProblem:
    Response.Write("An error occurred when the application executed")
    HourlySalary = 0
    WeeklyTime = 0

    Resume Next
    
End Sub
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmPayroll" 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 using the web page:

Error

Here is a example of making another calculation:

Error Handling

Types of Error

 

Introduction

In our introductions to errors, we mostly anticipated only problems related to arithmetic calculations. In reality, a program can face various categories of bad occurrences. The more problems you prepare for, the least headaches you will have. Problems are divided in two broad categories.

Syntax Errors

A syntax error occurs if your code tries to perform an operation that the Visual Basic language does not allow. If you are working with a Code Editor such as the one in Microsoft Visual Studio or in Microsoft Visual Web Developer, syntax errors are probably the easiest to locate because the Code Editor is configured to point them out at the time you are writing your code.

If you try typing or try inserting an operator or keyword in the wrong place on your code, the Code Editor would assist you to choose the right word or would underline your error. Here is an example:

Syntax Error

In this case, if you were trying to use the Do keyword instead of a data type (probably Double in this case), the Code Editor would show it right away:

Syntax Error

This type of error is pointed out for every keyword and operator you try to use.

Notice that, in the above example, we used a valid keyword but at the wrong time. If you mistype a keyword or an operator, you would receive an error. Fortunately, the Code Editor is equipped to know all keywords of the Visual Basic language. If you forget to include a necessary factor in your code, you would get a syntax error. For example, if you are creating a binary arithmetic expression that expects a second operand after the operator, you would receive an error.

These are just a few types of syntax errors you may encounter. As mentioned already, if you use the Code Editor to write your code, most of these errors are easy to detect and fix.

Run-Time Errors

A run-time error occurs when an application tries to do something that the operating system does not allow. In some cases, only your application would crash. In some other cases, the user may receive a more serious error. As its name indicates, a run-time error occurs when the program runs; that is, after you have created your application.

Fortunately, during the testing phase, you may encounter some of the errors so you can fix them before distributing your application. Some other errors may not occur even if you test your application. They may occur to the users after you have distributed your application. For example, you can create a car rental application that is able to display pictures 100% of the time on your computer while locating them from the E: drive. Without paying attention, after distributing your application, the user's computer may not have an E: drive and, when trying to display the pictures, the application may crash.

Examples of run-time errors are:

  1. Trying to use computer memory that is not available
  2. Performing a calculation that the computer hardware (for example the processor) does not allow. An example is division by 0 (the Intel and AMD processors are equipped not to allow division by 0)
  3. Trying to use or load a library that is not available or is not accessible, for any reason
  4. Performing an arithmetic operation on two incompatible types (such as trying to assign to an Integer variable the result of adding a string to a Double value)
  5. Using a loop that was not properly initialized
  6. Trying to access a picture not accessible. Maybe the path specified for the picture is wrong. Maybe your code gives the wrong extension to the file, even though the file exists
  7. Accessing a value beyond the allowable range. For example, using a Byte variable to assign a performed operation that produces a value the variable cannot hold

As you may imagine, because run-time errors occur after the application has been described as ready, some of these errors can be difficult to identify. Some other errors depend on the platform that is running the application (the operating system, the processor, the version of the application, the (available) memory, etc).

 
 
 

The Err Object

 

Introduction

To assist you with handling errors, the Visual Basic language provides a class named Err. You never have to declare a variable for this class. An Err object  is available whenever you start creating a Visual Basic project, and you can directly access its properties.

The Error Number

As mentioned already, there are various types of errors that can occur to a program. To assist you with identifying a problem, the Err class is equipped with a property named Number. This property is presented as follows:

Public Property Number() As Integer

This property holds a specific number to each sample error that can occur to a program. Because there are many types of errors, there are also many numbers, so much that we cannot review all of them. We can only mention some of them when we encounter them.

When a program runs, to find out what type of error occurred, you can question the Number property of the Err object to find out whether the error that has just occurred holds this or that number. To do this, you can use an If...Then conditional statement to check the number. You can then ask the compiler to display the necessary message 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)
    On Error GoTo ThereWasAProblem

    Dim HourlySalary As Double, WeeklyTime As Double
    Dim WeeklySalary As Double

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)
    WeeklyTime = CDbl(txtWeeklyTime.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * WeeklyTime

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

    Exit Sub

ThereWasAProblem:
    If Err.Number = 13 Then
        Response.Write("You typed an invalid value")
        HourlySalary = 0
        WeeklyTime = 0

        Resume Next
    End If
End Sub
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmPayroll" 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 running the program:

Error Handling

The Error Message

As mentioned already, there are many errors and therefore many numbers held by the Number property of the Err object. As a result, just knowing an error number can be vague. To further assist you with decrypting an error, the Err object provides a property named Description. This property holds a short message about the error number. This property works along with the Number property. It holds the message corresponding to each Number property.

To get the error description, after inquiring about the error number, you can get the equivalent Description value. Here is an example:

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

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    On Error GoTo ThereWasAProblem

    Dim HourlySalary As Double, WeeklyTime As Double
    Dim WeeklySalary As Double

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)
    WeeklyTime = CDbl(txtWeeklyTime.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * WeeklyTime

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

    Exit Sub

ThereWasAProblem:
    If Err.Number = 13 Then
        Response.Write(Err.Description)
        HourlySalary = 0
        WeeklyTime = 0

        Resume Next
    End If
End Sub
</script>

<title>Exercise</title>

</head>
<body>

<form id="frmPayroll" 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 running the program:

Error Handling

In some cases, the error message will not be explicit enough, especially if a user simply reads it to you over the phone. The alternative is to create your own message in the language you easily understand, as we did earlier. If you want, you can also display a message that combines the Err.Description message and your own message. Here is an example:

<script language="VB" runat="server">
Private Sub btnCalculateClick(Sender As Object, e As EventArgs)
    On Error GoTo ThereWasAProblem

    Dim HourlySalary As Double, WeeklyTime As Double
    Dim WeeklySalary As Double

    ' The following line may produce an error, such as
    ' if the user types an invalid number
    HourlySalary = CDbl(txtHourlySalary.Text)
    WeeklyTime = CDbl(txtWeeklyTime.Text)

    ' If there was an error, the flow would jump to the label
    WeeklySalary = HourlySalary * WeeklyTime

    txtWeeklySalary.Text = FormatNumber(WeeklySalary)

    Exit Sub

ThereWasAProblem:
    If Err.Number = 13 Then
        Response.Write(Err.Description & ": The value you typed cannot be accepted.")
        HourlySalary = 0
        WeeklyTime = 0

        Resume Next
    End If
End Sub
</script>

Here is an example of running the web page:

Error Handling

The Source of the Error 

Most of the time, you will know what caused an error, since you will have created the application. The project that causes an error is known as the source of error. In some cases, you may not be able to easily identify the source of error. To assist you with this, the Err object is equipped with a property named Source.

To identify the application that caused an error, you can inquire about the value of this property.

 
 
   
 

Home Copyright 2009 FunctionX, Inc.