Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

"On Error Goto HResume" works only once 3

Status
Not open for further replies.

NTSGuru

Programmer
Jul 25, 2000
52
I have a loop that is loading a set of data into a listview on form load. there are times when a piece of data will be unuseable, and it will error out my code. I placed a "On Error Goto HResume" as the first line within my While/Wend loop, where Hresume is the last line in my While/Wend loop.

This works great for the first error, but if there is a second error, it ignores the "On Error Goto HResume" and kills my app.

Does anyone know why this happens, and know of a fix? I have got to be able to have multiple error handles in a loop in this routine!

TIA
Fred


Follow
 
When the error occurs and VB transfers to your HResume label, VB internally turns on a flag that says you've entered an error handler, and disables error handling. An error handler is like a subroutine that must be exited before error handling is enabled again. Until you exit the error handler, which you do with a Resume or Exit Sub/Function or End Sub/Function statement, the internal flag is on and any further errors will not invoke the On Error branching. This is to prevent an infinite loop that would occur if your error handler encountered another error, which caused a branch to the error handler, which encountered another error, which....

The target label of On Error Goto should take execution out of line, with a Resume statement to get you back inline. Normally, the target label follows the body of the procedure, and an Exit Sub/Function statement precedes it so you don't "fall into" your error handler. Consider studying the Help file sections on writing error handlers.

You can modify your procedure like this:
Code:
    Private Sub Foobar()
        .
        .
        .
        On Error Goto ErrorHandler
        While somecondition
            do something
            do something else
    HResume:
        Wend
        On Error Goto 0
        .
        .
        .
        Exit Sub
    ErrorHandler:
        If Err.Number = theexpectederrornumber Then
            Resume HResume
        End If
        Err.Raise Err.Number
    End Sub
This code has the advantage that it doesn't treat all errors the same. If the expected error occurs, it simply continues. Otherwise it re-raises the error so you can figure out what happened right at the error source. If you're sure the only error that might happen is the one you expected, you can just use the Resume HResume statement as your error handler. Rick Sprague
 
That works beautifully!! Thanks much!

Fred
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top