Error handling

The ON ERROR RESUME NEXT, ON ERROR GOTO, ON ERROR GOSUB and ON ERROR STOP commands can be used to execute error handling in the code.

 

The following code triggers simple error handling. Error handling takes place in the code after the label defined behind the keyword LABEL. The On Error Gosub label command marks the error-handling routine. If an error is triggered (here by dividing by 0), the code is executed after the label and continues behind the code line that triggers the error.

 

Function DoAny(ByVal Parameter1 As Long) As Long

   On Error Gosub JumpLabel

  

   Parameter1 = Parameter1 / 0

 

   Exit Function Parameter1

  

Label JumpLabel

   MsgBox(Err.Description)

End Gosub

End Function

Alternatively, error handling can also be performed with the ON ERROR GOTO command:

 

Function DoAny(ByVal Parameter1 As Long) As Long

   On Error Goto JumpLabel

  

   Parameter1 = Parameter1 / 0

 

   Exit Function Parameter1

  

Label JumpLabel

   MsgBox(Err.Description)

End Function

 

In addition, the ON ERROR RESUME NEXT command is also available, which skips lines of code that cause errors. For error checking, the Err object is available, which provides the error code of the last error that occurred.

 

Function DoAny(ByVal Parameter1 As Long) As Long

   On Error Resume Next

  

   Parameter1 = Parameter1 / 0

End Function

 

The ON ERROR STOP command turns off error handling.

 

Function DoAny(ByVal Parameter1 As Long) As Long

   On Error Resume Next

  

   Parameter1 = Parameter1 / 0

 

   On Error Stop

End Function

 

Note that error handling also affects function calls. For example, if an error occurs in a called function after an error handling is switched on with ON ERROR RESUME NEXT, the command continues immediately after the function call in the error-handling function.

These error-handling chains are restarted when events are called. Therefore, a command may be required to handle errors at the beginning of an event.