Showing posts with label Languages. Show all posts
Showing posts with label Languages. Show all posts

Tuesday 7 August 2012

Understanding Error Handlers



When you use On Error GoTo and an error occurs, VB enters exception mode. The line you GoTo is supposed to be the beginning of an error handler. If an error occurs within an error handler, the program stops. What you need to do is leave the error handler and resume normal execution. Then you can use On Error to establish a new error handler for the next error. You do this with the Resume statement. See the help for details. In this case, you can use Resume LineLabel to make the program continue execution at a specific line.
Unfortunately, executing Resume from outside an error handler generates an error. Thus you cannot place the error handler in the flow of code the way you have. You need to jump out to the error handler and jump back with Resume.
Below is a subroutine that demonstrates two error handler.
Private Sub Command1_Click()
Dim i As Integer
On Error GoTo Error1
i = 1 / 0 ' Divide by zero.
Error1Resume:
On Error GoTo Error2
i = 1000000 ' Too big--overflow.
Error2Resume:
MsgBox "Finishing."
' Do not fall through into the error handlers!
Exit Sub
Error1:
' Resume ends error handler mode.
MsgBox "First error handler."
Resume Error1Resume
Error2:
' Resume ends error handler mode.
MsgBox "Second error handler."
Resume Error2Resume
End Sub

Total Pageviews

Extension Factory Builder