33

Why would you ever use "On Error Goto 0" in a VB6 app?

This statement turns the error handler off and would mean that any error would crash the app. Why would this ever be desirable?

14
  • 6
    Well, it's certainly a way of implementing fail-fast Apr 2, 2012 at 20:39
  • I don't have VB6 installed, but presumably any Goto statement to a non-existant label would crash the app.
    – Sam Axe
    Apr 2, 2012 at 20:40
  • This sounds like a comment from somebody who either throws in On Error Resume Next at the head of each procedure and then has mysterious woes that can't be diagnosed, or one who puts in On Error GoTo MyHandler and there just pops up a MsgBox with the same error anyway.
    – Bob77
    Apr 2, 2012 at 21:14
  • 3
    Not true at all. It is commonly paired with On Error Resume Next and a test of Err.Number to do inline structured error handling.
    – Bob77
    Apr 3, 2012 at 0:52
  • 2
    @CraigJ: Remember that the error handling is for that procedure (and children) only. "Turning it off" is NOT global, and allows errors to be handled by the parent.
    – Deanna
    Apr 3, 2012 at 15:28

5 Answers 5

59

In VB6, you can specify that you want errors to be handled by particular code later in the routine:

Sub Bar()
    On Error Goto MyHandler
    ...
    ...some code that throws an error...
    ...
    Exit Sub
MyHandler:
    ...some error handler code (maybe pops up a dialog)
End Sub

It may be the case, however, that the code that throws the error is localized, and you don't want that same handler for all of the rest of the code in the routine. In that case, you'd use "On Error Goto 0" as follows:

Sub Bar()
    ...
    On Error Goto MyHandler
    ...some code that throws an error...
    On Error Goto 0
    ...
    ...
    Exit Sub
MyHandler:
    ...some error handler code (maybe pops up a dialog)
End Sub

Now you have effectively scoped the error handling to execute only if that particular line of code fails.

By calling "On Error Goto 0" you are NOT saying that you want the app to crash immediately. You are simply saying that you want to de-register any error handlers that you may have set up earlier in the routine; errors will be passed up the call stack to calling routines, like normal.

3
  • 3
    You are also passing error handling up the stack to the calling procedure(s)
    – DJ.
    Apr 2, 2012 at 21:24
  • 1
    What if the current procedure is already at the bottom of the call stack? Can you see any use for it then? Because an error at that point would crash the app.
    – CJ7
    Apr 4, 2012 at 9:35
  • 7
    Craig, that would be no different than simply not having set up an error handler in the first place. By default, without any sort of error handling, the app will crash. It often makes sense, even at the top level, to be explicit about which lines of code have "active" error handling, then to turn it back off again. Suppose we want logging only if a certain bit of code fails. We should de-register the error handler after that. Error handling isn't always about preventing a crash; it could used for logging or cleaning up system resources. Crashing may be the desired (conscious) behavior. Apr 4, 2012 at 13:40
10

Since it seems to be clumsy to describe in words, here are some examples showing where you can use On Error GoTo 0 for localized, structured error handling.

The first is a Property Get in a class ("MicroDOM") that implements a lightweight DOM based on a hierarchy of subclassed Collections. In this case we want an attempt to reference a missing Child by name instead of index to create an empty (no attrbutes or children) Child:

Public Property Get Child(ByVal Key As Variant) As MicroDOM
    If mChildren Is Nothing Then
        Set mChildren = New Collection
    End If
    On Error Resume Next
    Set Child = mChildren(Key)
    If Err Then
        On Error GoTo 0
        If VarType(Key) = vbString Then
            Key = Trim$(Key)
            Set Child = New MicroDOM
            Child.Key = Key
            mChildren.Add Child, Key
        Else
            Err.Raise 9 'Subscript error as thrown by the Collection.
        End If
    End If
End Property

The second is inline code that deletes a file if it is present:

On Error Resume Next
Kill strFilePath
On Error GoTo 0

The third is inline code that takes an action only if a file happens to be present:

On Error Resume Next
GetAttr strFilePath
If Err Then
    On Error GoTo 0
    ProcessTheData strFilePath
End If
On Error GoTo 0

While it may appear awkward to the uninitiated (executing On Error GoTo 0 in two places) the result is less clumsy and more structured than having rafts of On Error GoTo Label that jump back and forth to process various exceptions.

The bonus is that you gain portability to VBScript as well, since On Error GoTo Label isn't a valid construct there at all.

7

It only turns off error handling in the CURRENT procedure. If there is an error handler in the calling procedure it will catch any exceptions that weren't handled. VB keeps going up the call stack until it finds an error handler. If it doesn't find any THEN it will cause the run-time error.

So for an example - maybe you have a wrapper function that calls some third-party utility that may throw an exception. Instead of handling the exceptions in the wrapper function you put a On Error Goto 0 in there. So then the caller of the wrapper function will then get the exception passed to it and hopefully handle it in a proper way.

3

You might find this link helpful: http://answers.microsoft.com/en-us/office/forum/office_2010-excel/why-on-error-resume-next-and-on-error-goto-0-have/a110548f-95c9-44ac-89bc-19697641804a?auth=1

Basically it explains that On Error Resume Next tells VB to skip any errors found and go to the next procedure or line in your code, while On Error GoTo 0 restores default error handling.

1

On Error GoTo 0 disables any enabled error handler in the current procedure and clears the Err object, which is not cleared by exiting the procedure where the error occurred. You insert this statement usually directly after the statement that might cause an error.

Example:

Function ShowError() As String
  Dim i As Long
  ShowError = "No error occurred!"
  On Error Resume Next
  ActiveDocument.Styles("codechar1").LanguageID = wdEnglishUS
  If (Not (Err Is Nothing)) Then ShowError = Err.Description 
  'On Error GoTo 0
End Function

Sub ApplyShowError()
  MsgBox ShowError & vbNewLine & Err.Description
 End Sub

Now suppose that the ActiveDocument object doesn't contain a style called codechar1. Then an error occurs and the function ShowError returns “The requested member of the collection does not exist.” If the On Error GoTo 0 line is commented out, the Err object is not cleared and survives the exit of the function ShowError, so this error message is outputted by the calling procedure again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.