Difference between Resume and Goto in error handling block
I understand that in the following example a Resume statement should be used instead of a Goto statement.
Sub Method()
On Error Goto ErrorHandler
...
CleanUp:
...
Exit Function
ErrorHandler:
Log error etc
Err.Clear 'Is this line actually necessary?'
Resume CleanUp 'SHOULD USE THIS'
Goto CleanUp 'SHOULD NOT USE THIS'
End Sub
My question is what difference i开发者_JAVA百科s there in the execution of the two?
Both transfer execution to the Cleanup
label. As far as I can remember, the only differences are
- Using
Goto
doesn't clear the Err object (soErr.Clear
is necessary if you useGoto
) and it leaves your error handler disabled. If an error occurs after theCleanup
label, it won't be handled atErrorHandler
. - Using
Resume
clears the Err object and it switches your error handler back on (it is disabled while it is handling errors). If an error occurs after theCleanup
lable, it will be handled atErroHandler
The VB6 manual entry for the Resume statement doesn't explain these differences.
This is BIG misunderstanding! There is important DIFFERENCE between:
Err.Clear
GoTo CleanUp
and:
Resume CleanUp
NEVER use the first form, ALWAYS use Resume CleanUp (only). Resume do the RESET of internal VB6 error state, so when OTHER error is occured, "On Error GoTo Label" will be applied. I you use "Err.Clear" then Err object is cleared, but INTERNAL error state is NOT cleared and when another error occure, it is considered as code WITHOUT any exception handler and throws outside of the function. You CAN NOT fix it by using "On Error GoTo Label2"
Consider this code:
Public Sub Test()
On Error GoTo L1
MsgBox 0 / (1 - 1)
Exit Sub
L1:
Err.Clear
L0:
On Error GoTo L2
MsgBox 0 / (1 - 1) 'ERROR!
Exit Sub
L2:
MsgBox Err
End Sub
If you run this, it will interrupt on "ERROR!" line. If you replace "Err.Clear" with "Resume L0" then execution does not interrupts on "ERROR!" line and code jumps to "L2" label and provides "MsgBox Err"
精彩评论