Difference between Resume and Goto in error handli

2020-06-01 07:49发布

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 is there in the execution of the two?

2条回答
劫难
2楼-- · 2020-06-01 07:53

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"

查看更多
虎瘦雄心在
3楼-- · 2020-06-01 07:58

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 (so Err.Clear is necessary if you use Goto) and it leaves your error handler disabled. If an error occurs after the Cleanup label, it won't be handled at ErrorHandler.
  • 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 the Cleanup lable, it will be handled at ErroHandler

The VB6 manual entry for the Resume statement doesn't explain these differences.

查看更多
登录 后发表回答