Raising an Error

The Err object has a Raise method that allows runtime errors to be raised when necessary. Here is the syntax:

Err.Raise number, source, description, helpfile, helpcontext

The number argument is required for raising an error, but the other arguments are optional. Here's an example to illustrate how you can raise an error in your code.

Sub TestErrRaise(intValue1 As Integer, intValue2 As Integer)

On Error GoTo HandleError

'declare variable to store result Dim intResult As Integer

If intValue2 <> 0 Then

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

'raise a custom divide by 0 error Err.Raise vbObjectError + 513, "TestErrRaise", _ "The second value cannot be 0."

End If

Exit Sub


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

End Sub

When the error is raised, the code then jumps to the error handler just as if the error had occurred in the traditional fashion.

0 0

Post a comment