vba 错误处理程序 - Exit Sub 与 End Sub

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1377152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:58:44  来源:igfitidea点击:

Error Handler - Exit Sub vs. End Sub

vbavb6error-handling

提问by AngryHacker

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?

为什么我想用 Exit Sub 退出 Error Handler(在处理之后),而不是让它进入 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

回答by AngryHacker

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

您的 ProcExit 标签是您释放所有资源的地方,无论是否发生错误。例如:

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

回答by Phil.Wheeler

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.

通常,如果您声明了数据库连接或其他对象,无论是安全使用还是在异常之前创建,都需要清理(处置),然后将错误处理代码返回到 ProcExit 入口点将允许您执行在这两种情况下你的垃圾收集。

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.

如果您通过退出子退出程序退出程序,您可能会冒着在程序内存中堆积一些令人讨厌的实例化对象的风险。