Error Handler - Exit Sub vs. End Sub

前端 未结 2 674
眼角桃花
眼角桃花 2021-01-07 18:20

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\'

相关标签:
2条回答
  • 2021-01-07 18:29

    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.

    0 讨论(0)
  • 2021-01-07 18:43

    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
    
    0 讨论(0)
提交回复
热议问题