PDA

View Full Version : GoTo versus Resume within an error-handling routine



tstav
04-04-2008, 11:55 AM
Here's something I learned the hard way (might save some of you a lot of wasted time).

It concerns the use of Error Handling routines and it focuses on the (rather hidden) difference it makes when you use "GoTo" instead of "Resume".

Check this short code snippet:
Sub Test()
On Error GoTo ErrorHandler
CheckAgain:
If CInt("abc") >= 0 Then
'This line will never run due to error trap
End If
ErrorHandler:
If Err Then
Err.Clear
GoTo CheckAgain
End If
End Sub
If you step through it (by F8) you'll see that on the first pass from CInt("abc") the apparent error will be silently caught by the ErrorHandler (as anticipated) and you will be sent to the ErrorHandler label.
Then, after the Err object gets cleared, the GoTo will send you back to the If CInt("abc") line for a re-evaluation.
But this time the error will not be trapped (surprise!?!) and an error message will interrupt the execution of the code.
Now change the "GoTo" to "Resume" and do a re-run. Voila! ErrorHandling works flawlessly.

The moral of the story:
When in an ErrorHandling routine, ALWAYS use "Resume".
"GoTo MyLabel" AND "Resume MyLabel" will both send you out of the error-handling routine over to MyLabel but "GoTo" seems to deactivate subsequent ErrorHandling.

P.S. VBA Help says: If you use a Resume statement anywhere except in an error-handling routine, an error occurs.
Well... that may be true but it sure misses my point that it is also IMPERATIVE that we use Resume when inside an error-handling routine, otherwise the error-handling goes out the window...

Thanks for listening and I'll be happy to get any feedback from you.

mikerickson
04-04-2008, 10:08 PM
The RESUME command tells the computer that the error handling routine is over. I think of it as clearing a hypothetical "in error handling mode" flag.

The GOTO is an instruction in the error handling routine. The "Handeling Error" flag is still set and the On Error instruction doesn't fire.

tstav
04-04-2008, 11:09 PM
Yes Mike,apparently that's exactly what Resume seems to do and GoTo not to do: Reset the "OnError" flag (or sth similar to this). Very well put. Thank you.