Reputation: 749
I have code like this, so when error is raised for the first time (c=1/0) then is going in error handle, after that it going in Again an if there is raised error than app is crashing, not going in error handler, any idea how to fix this?
On Error GoTo ErrorHandler maxretry=3 c=1/0 Again: c=a/b ErrorHandler: if maxretry>0 then maxretry=maxretry-1 goto Again end if
Upvotes: 3
Views: 438
Reputation: 1471
You'd rather use RESUME
than GOTO
in the error handler section:
On Error GoTo ErrorHandler
maxretry=3
c=1/0
Again:
c=a/b
ErrorHandler:
if maxretry>0 then
maxretry=maxretry-1
Resume Again
end if
Using RESUME
will, sort of, reset the internal error handler flag and giving you re-entrance in it (sort of).
Resume Again
tells VB6 to resume execution of code (after error is processed) at line labelled Again:
You could also use Resume Next
that tells VB6 to resume at the next instruction just after the one that causes the error.
If you want to retry your operation, you'll have to put another label and update your code that should most likely look like this:
On Error GoTo ErrorHandler
' Max number of tries.
maxretry = 3
Retry:
c = 1 / 0
NoMoreTry:
c = a / b
Exit Sub
' or Exit Function
' to avoid entering error handler because we don't need to
ErrorHandler:
If (maxretry > 0) Then
maxretry = maxretry - 1
' Try again, resume execution to "Retry" label.
Resume Retry
End If
' Tried 3 times, resume execution to "NoMoreTry" label.
Resume NoMoreTry
Be aware, in this particular case, that if your b variable is equal to 0 you'd probably have an infinite loop, because as c = a / b
will fail, then it goes to the error handler that will resume execution to NoMoreTry, then fail, ... and so on...
To avoid this, you can use On Error Resume Next
right after NoMoreTry, or add more code in the error handler.
Upvotes: 6