Results 1 to 21 of 21

Thread: On Error Goto Fails

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2007
    Posts
    448

    On Error Goto Fails

    Hello.

    I am trying to figure out why something so simple is failing. The following code fails to jump to DimArray1 when a Subscript Out Of Range error is encountered. Not much of a jump, since the label, "DimArray1:" is the very next line in the program after the failing line (I have heard somewhere to avoid using On Error Resume Next).

    The IDE is set to, "Break on Unhandled Errors".

    Code:
      On Error GoTo DimArray1
        MaxAmountGenericPoints = UBound(GenericPointsHistory, 2)
    DimArray1:
      On Error GoTo 0
    Thanks in advance!

  2. #2
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    14,205

    Re: On Error Goto Fails

    What does it do when the error happens on that line?

    May need to see more of the surrounding code

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2007
    Posts
    448

    Re: On Error Goto Fails

    Thanks for your reply, DataMiser.

    Quote Originally Posted by DataMiser View Post
    What does it do when the error happens on that line?

    May need to see more of the surrounding code
    The error gets raised and the program stops execution.

    Could it be due to having two On Error Goto's in the same procedure? The code shown in my OP, is proceeded further up with identical code, that exists within a For/Next block:

    Code:
        On Error GoTo DimArray2
        MaxAmountGenericPoints = UBound(GenericPointsHistory, 2)
    DimArray2:
        On Error GoTo 0
    I need to double-check why I have two instances of the code, and probably one of them can be deleted, but unless there is some problem with more than one On Error statement in the same procedure, this shouldn't be happening regardless.

  4. #4

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2007
    Posts
    448

    Re: On Error Goto Fails

    OK, I THINK I get it...I have enabled an error handler that is not separated from the general code in the procedure, by an intervening Exit Sub line. So even though I have used an On Error Goto 0 that should disable the handler, vb doesn't like the fact that I enabled ANOTHER error handler further down in the same procedure. If I really need both spots in my code to have the same error handling ability, I need to send both to the same error handler when in fact an error occurs. And, put that handler below all the code in the procedure, separated from that code with an Exit Sub line.

    UPDATE: Bummer...Didn't work.
    Last edited by treddie; Feb 27th, 2015 at 03:24 AM.

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2007
    Posts
    448

    Re: On Error Goto Fails

    Solved the problem, but not sure why it worked. I simply replaced both On Error Goto's with On Error Resume Next and the problem went away. Hmmmm.
    Last edited by treddie; Feb 27th, 2015 at 03:51 AM.

  6. #6
    PowerPoster
    Join Date
    Jun 2001
    Location
    Trafalgar, IN
    Posts
    4,141

    Re: On Error Goto Fails

    What did the whole procedure look like when it wasn't working?

  7. #7
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,538

    Re: On Error Goto Fails

    Quote Originally Posted by treddie View Post
    Solved the problem, but not sure why it worked. I simply replaced both On Error Goto's with On Error Resume Next and the problem went away. Hmmmm.
    No... it didn't go away, you're simply ignoring it... I think it was Si that said "VB is trying to tell you what the error is but you've chosen to stuff your fingers in your ears and not listen."

    to be honest, your original code was incorrect usage... Error handling is for error handling, not arbitrarily jumping around in your code, which is what you were effectively doing.

    what you should have done is this:

    Code:
    On Error GoTo errHandler
        MaxAmountGenericPoints = UBound(GenericPointsHistory, 2)
    
    ' do more stuff in your sub
    
    
    subExit:
      Exit Sub 'When done, exit out
    
    errHandler:
      'Handle the error - create the array, or message the user, or something.
      Resume 'Go back to the line that caused the error
      'Resume Next 'Or return back to the line after the one that caused the error
      'Resume subExit 'Or just simply bail
    When you enter an error handler, you have to RESUME out of it in order for any further error handling to work.. On Error Goto 0 or not... doesn't matter.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  8. #8
    Fanatic Member
    Join Date
    Jan 2013
    Posts
    765

    Re: On Error Goto Fails

    "On Error" <> "GoTo"

    When you set up "On Error Goto SomeWhere", you are declaring the code after the label "Something" to be an error handling routine. Within this routine there are a number of things you can do
    * Handle the error and make it go away,
    * Try whatever it was that failed again.
    * Continue your code with the next line after the one that failed.
    * "Return" from the error handler, branching to a specified label,
    * Exit the Sub or Function (or, even , program!)

    The important part is the "scope" of the error hander.

    "On Error Goto SomeWhere" makes the Somewhere "routine" the current error handler. When an error occurs, that's where the code branches to. But it's not a separate function, so the current error handler is still in force - if another error happens, it could branch to the Somewhere label again, but that would be silly so, instead, VB crashes the program, treating the second error as an unhandled one.

    The trick is to "turn off" the current error handler inside itself and set up a new one!

    Code:
    Sub Fred() 
       ' Set up an error handler 
       On Error Goto Error1 
    
       DoSomethingComplicated 
    
    Exxit:
       Exit Sub 
    
    Error1: 
       ' If DoSomethingComplicated goes wrong, we wind up here.  
       ' First, disable the current error handler.  
       On Error Goto -1 
    
       ' Start a new one  
       On Error Goto Error2 
    
       DoSomeComplicatedRecovery
    
       ' Return from the error handling routine. 
       Resume Exxit 
    
    Error2: 
       ' Error in the error handler! 
    
       ' Leave the error handling routine. 
       Resume Exxit
    
    End Sub
    Actually, in the case you mention, where you're testing for something very specific and only want to detect the error (and arrays and collections are prime candidates for this treatment), I would actually suggest the use of On Error Resume Next. (Yes, me!).

    Code:
    Dim oCollection as Collection : Set oCollection = New Collection 
    . . . 
    Dim sValue as String 
    
    On Error Resume Next 
    
       ' Function whose success/failure is to be tested 
       sValue = oCollection( sKeyValue ) 
    
       if ( 0 <> Err.Number ) then 
          ' Value is missing from collection. 
          . . .  
       end if 
    
    On Error GoTo 0
    Notice the matched pair of "Resume Next" and "Goto 0" (the default error handling for most, if not all, of my functions). I've trained myself to type these two statements as a single unit and then go back and insert the "testing" logic between the two; I will not type the one without the other.

    Regards, Phill W.

  9. #9
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: On Error Goto Fails

    Official VB6 documentation for On Error

    @Phil. On Error GoTo -1 ? Is that some undocumented option?
    .Net has it, but VB docs only reference On Error GoTo 0
    Last edited by LaVolpe; Feb 27th, 2015 at 10:52 AM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  10. #10
    Fanatic Member
    Join Date
    Jan 2013
    Posts
    765

    Re: On Error Goto Fails

    Looks like it's primarily used in VBA circles, but I've definitely got VB "proper" code that uses it as well.

    http://stackoverflow.com/questions/1...ror-goto-1-vba
    http://www.tutorialspoint.com/vba/vb...r_handling.htm

    Regards, Phill W.

  11. #11
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: On Error Goto Fails

    Quote Originally Posted by Phill.W View Post
    Looks like it's primarily used in VBA circles, but I've definitely got VB "proper" code that uses it as well.
    Yepper -- undocumented. Usage is key it appears. Looks like a way to set another error routine from within the current error routine.
    Code:
    Private Sub TestMe()
    On Error GoTo Catch1
        Debug.Print 1/0 ' generate an error
    Exit Sub
    
    Catch1:
        On Error GoTo -1
        On Error GoTo Catch2
             Debug.Print 1/0 ' generate an error
        Exit Sub
    Catch2:
         Debug.Print "Error handled in Catch2"
    End Sub
    Some notes:
    1) If "On Error GoTo -1" were removed, the error generated in the Catch1 routine would not be rerouted anywhere, error would be raised & unhandled.

    2) If "On Error GoTo Catch2" were removed, the error generated in Catch1 would return to Catch1. This causes an infinite loop. Last thing you want is your error trapping causing an infinite loop

    3) So, within an error routine, if using On Error GoTo -1, ensure you follow it with a new On Error statement else be prepared for the routine to be re-entered if a new error occurs within the error routine

    Quote Originally Posted by techgnome
    ... I don't think it's valid with in main code
    Appears true. Adding On Error GoTo -1 outside of the error routine doesn't seem to have any effect
    Last edited by LaVolpe; Feb 27th, 2015 at 04:14 PM.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  12. #12
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,538

    Re: On Error Goto Fails

    It's only valid in the error handler itself, for those cases where you have an error handler that can go wrong (such as logging to a file that's missing, or unable to write to, or your database server fell off the edge of the world and is no longer accessible) ... I don't think it's valid with in main code... man... that's some knowledge that goes waaaaaaay back. I think I may have written that once or twice in all these years, and it goes back to VB3, which is probably the first & last time I did one of those - we had to be adaptable in case the network suddenly became unavailable - and back in those days... it happened more than we would have liked.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  13. #13
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,163

    Re: On Error Goto Fails

    On Error GoTo -1 looks like a neat hack! Will use it immediately.

    cheers,
    </wqw>

  14. #14

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2007
    Posts
    448

    Re: On Error Goto Fails

    GAWD I hate undocumented features! Knowing that little gem now is...well...a Gem!

    Thanks for all the great responses! I will report back after I have experimented with the suggestions.

  15. #15

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2007
    Posts
    448

    Re: On Error Goto Fails

    Had fun playing around with On Error Goto -1. Very useful for problems in the error handler itself. Which is kind of funny...An error in an error handler! Lol!

    And the combination of On Error Resume Next with On Error Goto 0 is cool, too. But as in my case, if I only need to test for the EXISTENCE of an error and nothing more (no error handling required beyond detection), shouldn't On Error Goto 0 be replaced by On Error Goto -1, so that error handling can be reset to be used again within the same procedure? But then again, I am getting the feeling that On Error Resume Next w/ On Error Goto 0 is doing exactly that...The Resume part is essentially doing an On Error Goto -1? But if that is the case, why even follow up with On Error Goto 0?
    Last edited by treddie; Mar 1st, 2015 at 01:30 AM.

  16. #16
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: On Error Goto Fails

    Not sure about your tests or wording...

    Look at this simple example. On Error GoTo -1 is not the same as On Error GoTo 0. the -1 only resets within the error routine, not outside of it.
    Code:
    Private Sub TestErr()
    On Error GoTo ErrH
    On Error GoTo -1 ' replace -1 with 0 and try again
    Debug.Print 1 / 0
    Exit Sub
    
    ErrH:
        Stop
    End Sub
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  17. #17

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2007
    Posts
    448

    Re: On Error Goto Fails

    So there seem to be two things going on:
    1. An error handling (object?) is created with On Error Goto and On Error Resume, which is dealt with through an error handler.
    2. Once that error (object?) is created you can do two things with it in the handler:
    a. Respond to the error, clear the error info, and leave the error object alive with On Error Goto 0.
    b. Respond to the error, clear the error info, but destroy the error object with On Error Goto -1.

    If that is true, why use On Error Goto 0 at all? Seems like it just leaves dirty laundry in memory while the procedure is still running?

  18. #18
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: On Error Goto Fails

    On Error GoTo 0 does not clear the error, it terminates error routing and any future errors after that line are unhandled in that sub/function. If an error does occur after On Error GoTo 0, then it is bumped up the whatever method(s) called the one that generated the error until an error routine is found or none exists, which then is fatal.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  19. #19

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2007
    Posts
    448

    Re: On Error Goto Fails

    When you say, "clear the error", what exactly does that mean. If I do:

    Code:
    ErrHandler:
      Dim ErrNum as Byte
      Dim a as Byte
    
      a = Err.Number
      On Error Goto 0
      a = Err.Number
    
      Resume
    The first instance of (a) returns the error number, the second returns "0". So hasn't the error info been cleared via On Error Goto 0, while still leaving the error object in memory?

  20. #20
    Frenzied Member
    Join Date
    Mar 2008
    Posts
    1,210

    Re: On Error Goto Fails


  21. #21

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2007
    Posts
    448

    Re: On Error Goto Fails

    That's in the vb help system, but it really doesn't say much more than suggest that On Error Goto 0 dumps the error number but leaves an enabled and functionless error handler in memory. If that weren't true, On Error Goto 0 would clear everything and you could immediately start back up with a new On Error Goto MyErrorHandler, without issue, while never leaving the procedure. As it stands On Error Goto 0 seems very sloppy to me. It leaves trash that you're stuck with.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width