We always want 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 should predict 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:

If you simply create a label and its
message like this, its section would always execute. Here is an example:

Module Exercise
Public Function Main() As Integer
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(InputBox("Enter the employee's hourly salary:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * 40
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
ThereWasAProblem:
Console.WriteLine("An error occurred when the application executed")
Return 0
End Function
End Module

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 Sub before the label. This would be done as follows:

Module Exercise
Public Function Main() As Integer
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(InputBox("Enter the employee's hourly salary:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * 40
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Exit Function
ThereWasAProblem:
Console.WriteLine("An error occurred when the application executed")
Return 0
End Function
End Module

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:

Module Exercise
Public Function Main() As Integer
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(InputBox("Enter the employee's hourly salary:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * 40
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Exit Function
ThereWasAProblem:
Console.WriteLine("An error occurred when the application executed")
Return 0
End Function
End Module

The On Error GoTo indicates to the compiler where to
transfer code if an error occurs. Here is an example of running the program:

An error occurred when the application executed
Press any key to continue . . .

Go to a Numbered Label

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

Module Exercise
Public Function Main() As Integer
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(InputBox("Enter the employee's hourly salary:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * 40
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Exit Function
28:
Console.WriteLine("An error occurred when the application executed")
Return 0
End Function
End Module

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:

Module Exercise
Public Function Main() As Integer
On Error GoTo 28
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(InputBox("Enter the employee's hourly salary:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * 40
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Exit Function
28:
Console.WriteLine("An error occurred when the application executed")
Return 0
End Function
End Module

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:

Module Exercise
Public Function Main() As Integer
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(InputBox("Enter the employee's hourly salary:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * 40
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Return 0
End Function
End Module

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:

Module Exercise
Public Function Main() As Integer
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(InputBox("Enter the employee's hourly salary:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * 40
Resume
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Exit Function
ThereWasAProblem:
Console.WriteLine("An error occurred when the application executed")
Return 0
End Function
End Module

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:

Module Exercise
Public Function Main() As Integer
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(InputBox("Enter the employee's hourly salary:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * 40
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Exit Function
ThereWasAProblem:
Console.WriteLine("An error occurred when the application executed")
Resume Next
Return 0
End Function
End Module

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:

Module Exercise
Public Function Main() As Integer
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(InputBox("Enter the employee's hourly salary:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * 40
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Exit Function
ThereWasAProblem:
Console.WriteLine("An error occurred when the application executed")
HourlySalary = 0
Resume Next
Return 0
End Function
End Module

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

Module Exercise
Public Function Main() As Integer
On Error GoTo ThereWasAProblem
Dim HourlySalary As Double, WeeklyTime As Double
Dim WeeklySalary As Double
' One of these two lines could produce an error, such as
' if the user types an invalid number
HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))
WeeklyTime = CDbl(InputBox("Enter the time worked for the week:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * WeeklyTime
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Time: {0}", FormatNumber(WeeklyTime))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Exit Function
ThereWasAProblem:
Console.WriteLine("An error occurred when the application executed")
HourlySalary = 0
WeeklyTime = 0
Resume Next
Return 0
End Function
End Module

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. These 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 point it out by underlining
it. Here is an
example:

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. 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. Consider the following example:

The programmer mistyped the Mod operator and wrote MAD
instead.

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. Here is an example:

In this case, the programmer pressed Enter after the Mod
operator, as if the expression was complete. This resulted in 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:

Trying to use computer memory that is not available

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)

Trying to use or load a library that is not available or is not
accessible, for any reason

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)

Using a loop that was not properly initialized

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

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:

Module Exercise
Public Function Main() As Integer
On Error GoTo ThereWasAProblem
Dim HourlySalary As Double, WeeklyTime As Double
Dim WeeklySalary As Double
' One of these two lines could produce an error, such as
' if the user types an invalid number
HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))
WeeklyTime = CDbl(InputBox("Enter the time worked for the week:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * WeeklyTime
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Time: {0}", FormatNumber(WeeklyTime))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Exit Function
ThereWasAProblem:
If Err.Number = 13 Then
MsgBox("You typed an invalid value")
HourlySalary = 0
WeeklyTime = 0
Resume Next
End If
Return 0
End Function
End Module

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:

Module Exercise
Public Function Main() As Integer
On Error GoTo ThereWasAProblem
Dim HourlySalary As Double, WeeklyTime As Double
Dim WeeklySalary As Double
' One of these two lines could produce an error, such as
' if the user types an invalid number
HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))
WeeklyTime = CDbl(InputBox("Enter the time worked for the week:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * WeeklyTime
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Time: {0}", FormatNumber(WeeklyTime))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Exit Function
ThereWasAProblem:
If Err.Number = 13 Then
MsgBox(Err.Description)
HourlySalary = 0
WeeklyTime = 0
Resume Next
End If
Return 0
End Function
End Module

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:

Module Exercise
Public Function Main() As Integer
On Error GoTo ThereWasAProblem
Dim HourlySalary As Double, WeeklyTime As Double
Dim WeeklySalary As Double
' One of these two lines could produce an error, such as
' if the user types an invalid number
HourlySalary = CDbl(InputBox("Enter the employee's hourly salary:"))
WeeklyTime = CDbl(InputBox("Enter the time worked for the week:"))
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * WeeklyTime
Console.WriteLine("Hourly Salary: {0}", FormatNumber(HourlySalary))
Console.WriteLine("Weekly Time: {0}", FormatNumber(WeeklyTime))
Console.WriteLine("Weekly Salary: {0}", FormatNumber(WeeklySalary))
Exit Function
ThereWasAProblem:
If Err.Number = 13 Then
MsgBox(Err.Description & ": The value you typed cannot be accepted.")
HourlySalary = 0
WeeklyTime = 0
Resume Next
End If
Return 0
End Function
End Module

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.