views:

317

answers:

2

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
+1  A: 

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.

Phil.Wheeler
Poor choice of words. "Do your garbage collection" and "sitting around in your program's memory". This might encourage religously setting all local object references to Nothing at the end of the routine. In fact objects and memory will be automatically garbage collected by VB6 as soon as the reference count goes to zero. If they were in local variables, this happens at the Exit Sub. You only have to worry in relatively few cases, where special resources need to be explicitly released or when some other state needs to be restored (e.g. change mouse pointer back from hourglass).
MarkJ
Fair point. Best brush up on my VB6 I suppose. Been too focussed on modern, object-oriented fun languages lately anyway...
Phil.Wheeler
You still may need "clean up" though beyond simply dropping object references by exiting their scope. You might be holding a reference to an out of process server that requires an explicit shutdown request (e.g. Excel may be waiting for a Quit call). Or you might want to release a reference declared outside the procedure's own scope on exit.
Bob Riemersma
+9  A: 

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
AngryHacker
+1. And, obviously, if you don't need to close or release any resources, there's no need for it and you can just fall through to the End Sub.
MarkJ
@MarkJ: Thats probably Ok but I'd be uncomfortable with that, If the error has truely been "handled" I'd prefer to Resume to ProcExit even if its immediately followed with Exit Sub.
AnthonyWJones
Wouldn't this cause an infinite loop if something below `ProcExit` raises an error?
Mike Spross