Error Handler - Exit Sub vs. End Sub

2019-02-16 05:45发布

Why would I want to get out of an Error Handler (after handling) with an Exit Sub instead of just letting it go to the End Sub?

I'm sure it's simple. I just don't understand. Thanks for any help.

Example:

Public Sub SubA()
On Error Goto ProcError

  ''# other code  
  MsgBox FuncA()

ProcExit:  
  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

2条回答
可以哭但决不认输i
2楼-- · 2019-02-16 06:17

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub
查看更多
欢心
3楼-- · 2019-02-16 06:21

Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.

If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.

查看更多
登录 后发表回答