0 votes
in VBA by Beginner (23 points)

There is no statement in the code labelled 0. So What does GoTo 0 mean?

1 Answer

+1 vote
by Beginner (86 points)
selected by
 
Best answer

Dear sandeep kothari,

     The full syntax of the On Error statement is:

On Error Goto Label
On Error Goto 0
On Error Goto -1
On Error Resume Next 

where Label is an identifier that marks a certain block of code within the function body. About the On Error Goto 0 statement the official Microsoft documentation says:

On Error GoTo 0 disables error handling in the current procedure. It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0. Without an On Error GoTo 0 statement, an error handler is automatically disabled when a procedure is exited.

As you said, even if there isn't a block of code labelled 0, this instruction tells the interpreter to disable an error handler previously defined in a function's body. So you should be aware that:

  1. The On Error GoTo 0 statement disables any error handler declared in the body of the function (if any, otherwise it does nothing).
  2. Any error handler within the body of the function is disabled at the exit from the function, even if there is no On Error GoTo 0 statement.
  3. The On Error GoTo 0 statement doesn't affect any statements before it. Yo can think of it a a closing bracket for a try { ... } catch { ... } statement in Java Script. It limits the scope (the sequence of statements) on which an error handler acts.

Ryan Wells gives and example of such a statement when checking a file for existence. I'll post it here:

Function FileExists(FilePath As String) As Boolean
    Dim TestStr As String
    TestStr = ""
    On Error Resume Next
    TestStr = Dir(FilePath)
    On Error GoTo 0
    If TestStr = "" Then
        FileExists = False
    Else
        FileExists = True
    End If
End Function

In the body of the FileExists function an error handler has been set up by On Error Resume Next, meaning that if an exception is raised within the body of that function, excecution will resume at statement immediatlery after the one that raised the exception. By using On Error GoTo 0, we disable that handler, meaning that if an exception is raised by the code following the On Error GoTo 0 statement, then the exception will be passed down on the stack, because in the function body there isn't any active error handler. So the On Error GoTo 0 statement limit the scope of the error handler to just TestStr = Dir(FilePath). Ryan Wells has done that so that if the Dir() function raises an exception, the Resum Next catches it.

In Python the code would have looked like:

def file_exists(path):
    teststr = ""
    try:
        teststr = dir(path)
    except Exception:
        pass
    if teststr == "":
        return False
    else:
        return True

where dir() is a fictional function with the same meaning as Dir(). Here except has the same function as On Error GoTo 0, i.e. to confine the actions of the error handling code to the statements between try and except. (There are better ways of testing a file for existence in Python)

by Beginner (23 points)
Thanks for your detailed answer.

Let's stick to VBA.

ON ERROR GoTo 0

I remember in BASIC code, we used GoTo 0 to make the code execute line no. 0 in the code. But in VBA, ON ERROR GoTo 0 does not seem to act similarly. Please clarify.
by Beginner (86 points)

I'll try to clarify my point even more: the On Error GoTo 0 statement marks the point within the body of a function where all previous error handlers are disabled. It has nothing to do with jumping to a instruction labelled by 0. Generally, the GoTo statement jumps to the label, but in this particular case the doesn't stand for a label. If it helps you, you may think of it as an instruction called Disable Handlers

by Beginner (23 points)
Is it Disable Handlers or should it be Enable Error Handler?
by Beginner (86 points)

No, it is Disable Handlers. Let me put it other words. Suppose that in the body of a function you put a statement like On Error GoTo ErrorHandler (where ErrorHandler is a label you define somewhere else in the body of the function, containing the code you want to use to handle the exception). This error handler will act on all the code from it to the end of the function body. You may want to limit it to just a few istructions, e.g. because the other instructions won't raise any exception. That's where On Error GoTo 0 come in handy. It basically says: all the previous error handlers in the body of this function are disabled. That's what Ryan Wells does in his example: since the If ... Else statement at the bottom of the function body won't raise any exception, it limits the scope of the On Error Resume Next handler to just TestStr = Dir(FilePath). Let me know if you have any doubts about that.

by Beginner (21 points)

Alberto: What is On Error Goto -1? You listed this in your full syntax. What does it do? I've never seen in in VBA.

by Beginner (86 points)
edited by

Dear JWoolley,

    the On Error GoTo -1 statement exits the error-handling mode, and resumes the execution of the function. It both clears the current exception object, and clears all error handlers (like On Error GoTo 0 does). The official documentation is not that clear about it, and states:

On Error GoTo -1 disables the exception in the current procedure. Without an On Error GoTo -1 statement, an exception is automatically disabled when a procedure is exited.

Your error handling code may be structured as follows: 

  1. Assign a new error handler with a GoTo Label statement.
  2. Use GoTo 0 to limit the scope of the code protected by error handlers.
  3. In the body of an error handler, use GoTo -1 both to end the error handler's scope and to exit the error-handling mode, so that you can register a new error handler after the previous one has caught an exception.

You can use one of the following statements to exit from error-handling mode:

  • Exit Sub or Exit Function
  • On Error Resume Next
  • On Error GoTo -1
  • Reaching the end of the function or subroutine's body.

While in error handling mode, the program doesn't behave as expected, notably, it can use another On Error GoTo Label statement to jump to another error handling code. If your error handling code raises an exception, the program will crash, because it cannot handle the new exception. Let's see an example:

Function CheckedDivision(i, j As Integer) As Integer
    On Error GoTo ZeroDivisionHandler  ' set an error handler
    i = i \ j                          ' it may raise an exception
    CheckedDivision = i
    Exit Function

ZeroDivisionHandler:
    ' do something useful here
    On Error GoTo -1                   ' exit error-handling mode
    On Error GoTo ZeroDivFaultyHandler ' set another error handler
    i = i \ j                          ' it may raise an exception
    CheckedDivision = i
    Exit Function

ZeroDivFaultyHandler:
    On Error GoTo 0  ' disable all handlers, still in error-handling mode
    On Error Resume Next      ' cannot set another error handler while in error-handling mode
    i = i \ j        ' uncaught exception
    
    CheckedDivision = i
End Function

The example works as follows:

  1. The ZeroDivisionHandler handles the first exception. Then it both clears the exception object and all previous error handlers. Then, it sets the new error handler ZeroDivFaultyHandler.
  2. Another exception is raised, but now ZeroDivFaultyHandler is in charge of handling exceptions.
  3. The ZeroDivFaultyHandler uses On Error GoTo 0 to limit the scope of the error handling code, but it doesn't clear the exception object, so we are still in exception-handling mode.
  4. The On Error Resume next statement tries to register a new error handler, but it won't succed, because in error-handling mode you cannot register another handler.
  5. The i = i \ j statement will raise an exception that won't be caught, since there isn't an active error handler, so the program will crash.

The example is a little bit silly, but I think I made my point.

 

Alberto Semat

by Beginner (21 points)

Alberto: Thank you for the detailed explanation. After changing Resume Next to On Error Resume Next in your example, I think I understand it now. But it's curious that On Error GoTo -1 is not mentioned in Microsoft's Office VBA Language Reference.

by Beginner (86 points)

Thank you for pointing out my error, I've corrected it. I don't know why this statement is not mentioned in the official documentation. Are they ashamed of it? To be fair, there is little use for it, and it is error-prone. Moreover, both the On Error GoTo 0 and the On Error GoTo -1 statements are counterintuitive. They could have picked better names for both of them. I don't know the evolution of the language, but they look like patches to me. That's the way of the world. 

Welcome to wellsr Q&A
wellsr Q&A is the VBA and Python programming community that rewards you for learning how to code.

Earn free prizes for asking VBA and Python questions and for answering questions asked by others in our community.

What makes us different?
Our points system rewards you with a chance for free gifts based on the quality of your questions and/or answers. Users that ask great questions, may be given complimentary gift cards or training material.

Getting Started
Register
VBA Cheat Sheets

So, why don't you join us? It really is a neat way to reward the most dedicated members in our VBA and Python community.

For more programming tips visit the VBA Tutorials Blog and the Python Tutorials Blog.

...