Home > Software engineering >  Even without an Error, the code for "Line3:" still gets run on On Error GoTo Line3
Even without an Error, the code for "Line3:" still gets run on On Error GoTo Line3

Time:01-03

Example Code:

On Error GoTo Line3

More code

Line3:
    Some code
    Some code

More code

Even when there is no error, the "some code" underneath Line3 still gets run even though I don't want it to run. Otherwise when there is an error, Line3 gets run appropriately (skipping code that comes before it like it should).

CodePudding user response:

The code will still run, it's just a label you can point the execution to if need be.

Try this to avoid your problem but without knowing your exact requirement, you’ll likely need to tweak the code structure to suit your needs.

My suggestion would be to put Line3 at the bottom, not in the middle of the routine. That way you just do a clean up and then get out. It tends to make more sense from a readability perspective. Of course, you should only do that if it makes sense to get out after the error occurs.

    On Error GoTo Line3

    More code

    Goto Line4

Line3:
    Some code
    Some code

Line4:
     On Error GoTo 0

     More code

The trick with GoTo statements (if you intend to use them) is to use them sparingly.

CodePudding user response:

Using Gotos to manage execution paths is almost always a poor design choice. You could consider the following approach that does not rely so heavily on Goto labels. It is easier to see the intended logic flow (and error handling) without having to visually parse any Goto statements.

Sub Example()
    If Not TryMorecode1() Then
        Somecode1
        Somecode2
    End If

    Morecode2
End Sub

Private Function TryMorecode1() As Boolean
    'catch errors locally within this function
    'return False if an error is generated
End Function

Private Sub Morecode2()
End Sub

Private Sub Somecode1()
End Sub

Private Sub Somecode2()
End Sub
  • Related