为什么从错误处理程序块内部退出子程序是错误的? [英] Why is it wrong to exit a sub from inside of a error handler block?

查看:32
本文介绍了为什么从错误处理程序块内部退出子程序是错误的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某处读到不建议退出错误处理块.遗憾的是,他们没有解释原因?

I read somewhere that exiting out of an error handling block is not recommended. Sadly they did not give an explanation why?

我很好奇为什么会这样.我确实在 On Error Goto 0"的讨论中找到了与此相关的内容.在 Exit Function 之前,但不确定这是否是最终答案.他们谈论的是 Err 对象没有被清除.这是唯一的问题吗?如果是,有解决办法吗?

I was curious why is it so. I did find something related to this in the discussion at "On Error Goto 0" before Exit Function but not sure if that is the definitive answer. They talk about the Err object not being cleared. Is that the only issue and if so is there a work around?

这是错误的吗?如果是,那么退出函数的推荐方式是什么?我不是 go to 语句的大力支持者,它们使代码更难遵循.

Is this wrong? If it is, then what is the recommended way of exiting the function? I am not a huge supporter of go to statements, they make the code harder to follow.

    Private Sub Foo2()
        On Error Resume Next
            'Multiple lines of code

            If Not Foo(arg1,arg2) Then
                Exit Sub  'Can I exit here?
            End If

            'Multiple lines of code
        On Error GoTo 0
    End Sub

推荐答案

除了关于 On Error Resume Next 的警告(注意他们!!),这段代码没有任何问题.错误处理语句的作用域是 Foo2 Sub,当你退出它时它就会过期.当您在 For 块中调用另一个 Sub 时会出现危险,它本身可能会调用其他 Sub.那些 subs 将继承 On Error Resume Next 并且当从他们提出的错误被吞下时会给你带来多年的噩梦......

Apart from the warnings about On Error Resume Next (heed them!!) there are no problems with this code. The scope of the error handling statement is the Foo2 Sub, it will expire when you Exit it. The dangers arise when you call another Sub within the For block, which in itself may call other Subs. Those subs will inherit the On Error Resume Next and will give you nightmares for years on end when Errors raised from them are swallowed...

这篇关于为什么从错误处理程序块内部退出子程序是错误的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆