Error handling

Errors happen! If there is a critical place in the program where we think that an error may occur it is necessary to mark it and further redirect the program flow to the message that should be displayed if it occurs. For managing the program flow, with and without error, we can use the GoTo command. In combination with On Error we get a powerful tool that helps us take the necessary action immediately after the error is detected.

Let’s first see how the GoTo command is used. Its syntax is:

GoTo <label>

It always redirects the program flow to, pre-set label. Let’s see how it works in the case:

Sub GT()

Dim a As Integer
GoTo Init
a = 10
a = 20
MsgBox a

End Sub

After we launch the program it will display a value of 20 in the dialog box. Why did this happen? Because we redirected the program to the Init label after which the value assignment is made to the variable. Let’s now review a simple error processing scenario:

Sub EH()

Dim a, b As Integer
Dim c As Single
a = 10
b = InputBox(“Enter a value”)
On Error GoTo L1
c = a / b
MsgBox c
GoTo L2:
MsgBox (“Error!”)

End Sub

The goal of the program is to divide the number 10 with the second entered number. If user enters a value of 0 an error occurs (division by zero) and instead of terminating the program it will be redirected to an error message.