Resume Statement

The Resume and Resume Next statements can be used with the On Error statement. The Resume statement will cause code execution to resume at the line that caused the error, and the Resume Next statement will cause code execution to resume at the line following the one that caused the error. Resume statements are commonly added within the error-handler routines, such as the one shown here.

Sub Test()

On Error GoTo HandleError 'normal code for the procedure goes here Exit Sub

HandleError:

'code for handling the error goes here

Resume Next

Exit Sub End Sub

Try It Out Creating an Error Handler

It is your turn to try your hand at creating an error handler.

1. Place the following code for a new procedure called TestError in the modBusinessLogic standard module:

Sub TestError(intValue1 As Integer, intValue2 As Integer)

On Error GoTo HandleError

'declare variable to store result Dim intResult As Integer

'calculate result by dividing first value by second value intResult = intValue1 / intValue2

Exit Sub

HandleError:

MsgBox "An error has occurred in your application: " & Err.Description Exit Sub End Sub

2. Run the TestError procedure from the Immediate Window, as shown in Figure 2.41.

Figure 2.41

3. The following error message (shown in Figure 2.42) is displayed.

Figure 2.42

How It Works

The TestError procedure accepts two variables as parameters.

Sub TestError(intValue1 As Integer, intValue2 As Integer)

The On Error statement indicates that the HandleError section of code should execute when an error occurs.

On Error GoTo HandleError

A variable is declared that will be used to store the result of an upcoming mathematical calculation.

'declare variable to store result Dim intResult As Integer

The intValue1 value is then divided by the intValue2 value.

'calculate result by dividing first value by second value intResult = intValue1 / intValue2

Because the intValue2 value you specified when calling the procedure was set to 0, a divide by 0 error occurs when the preceding line of code executes. Thus, the execution of code then jumps to the error handler HandleError at the bottom of the procedure.

HandleError:

MsgBox "An error has occurred in your application: " & Err.Description Exit Sub End Sub

A message box is then displayed to indicate that an error has occurred and to provide a description of the error.

0 0

Post a comment