0

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

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?

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
4

4 回答 4

1

如果我正确理解您的问题,更好的方法是执行以下操作:

Private Sub Foo2()
    On Error Goto ErrHandler
        'Multiple lines of code

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

        Multiple lines of code

ErrHandler:
    Error handling mechanism here.
End Sub
于 2012-05-09T05:20:35.037 回答
1

除了关于On Error Resume Next(注意他们!!)的警告之外,此代码没有任何问题。错误处理语句的范围是 Foo2 Sub,当你退出它时它会过期。当您在 For 块中调用另一个 Sub 时,就会出现危险,而后者本身可能会调用其他 Sub。这些潜艇将继承 On Error Resume Next,当从它们引发的错误被吞下时,它们会给你带来多年的噩梦......

于 2012-05-09T09:07:47.950 回答
0

在我过去使用 VB6 的经验中,使用 Resume Next 并不是一个好主意。我从来没有用过它。我的代码尽最大努力避免错误,并且在发生错误的情况下,它总是会归结为错误处理程序块。您链接到的问题说明了我大量使用的 MZTools 的使用。

所以,我的观点是,Resume Next 代码很可能只是一个练习,而不是真正的生产代码。如果这是真的,那么您不必在 Exit Sub 之前清除 Err 对象,因为 Err 对象无论如何都不会包含任何内容。如果您确实遇到错误,它将转到 ErrorHandler 标签并从那里继续。我是那个处理程序,是的,理想情况下,您希望对 Err 对象做一些事情,然后适当地返回给调用者。

于 2012-05-09T06:28:14.927 回答
0

我会重新排列你的代码行,并确保退出子或退出函数总是出现在 ErrorHandler 之前:

Private Sub Foo2()
   On Error Goto ErrHandler

    'Multiple lines of code

    If Foo(arg1,arg2) Then

        'Multiple lines of code

    End If

    Exit Sub

  ErrHandler:
    Error handling mechanism here.
End Sub
于 2012-05-11T14:12:01.340 回答