发生错误时,Goto在EventHandler子内部不起作用 [英] On Error Goto doesn't work inside EventHandler subs

查看:53
本文介绍了发生错误时,Goto在EventHandler子内部不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设以下代码:

Module1:

Sub main()

    Dim cl As New Class2
    On Error GoTo errorhandler1
        cl.DoWork
     On Error GoTo 0
Exit Sub

errorhandler1:
    MsgBox (Err.Description)

End Sub

Class1:

Event MyEvent()

Public Sub DoWork()
    RaiseEvent MyEvent
End Sub

Class2:

Private WithEvents cl As Class1

Private Sub cl_MyEvent()
    Call Err.Raise(123, , "ErrorInClass")
End Sub

Private Sub Class_Initialize()
    Set cl = New Class1
End Sub

Public Sub DoWork()
    cl.DoWork
End Sub

我希望errorhandler1启动,并显示带有err.Description的MsgBox.但是,它却引发了我运行时错误.

I expect errorhandler1 to launch and MsgBox with err.Description to be shown. But it throws me runtime error instead.

在EventHandlers例程中如何处理错误?

What I have to do to handle errors within EventHandlers routines?

推荐答案

我们可以阅读此处:

如果使用Err对象的Raise方法引发错误,则表示可以强制Visual Basic在呼叫列表中向后搜索已启用的错误处理程序.

If you use the Raise method of the Err object to raise an error, you can force Visual Basic to search backward through the calls list for an enabled error handler.

但是在这种情况下,没有启用的错误处理程序.

But in this case there is no enabled error handler.

也许您可以通知class2的客户工作失败.在这里,因为class2的客户端是一个标准模块,所以您不能使用class2的事件,所以也许一个简单的只读属性可能对您有帮助?

Maybe you could inform the client of class2 that the work failed. Here because the client of class2 is a standard module you can't use events from class2, so maybe just a simple read-only property might help here?

模块:

Sub main()
    cl.DoWork
    If Not cl.IsWorkOk Then MsgBox "Work failed..."
    On Error GoTo 0
    Exit Sub

errorhandler1:
    MsgBox (Err.Description)

End Sub

Class2:

Class2:

Private m_isWorkOk As Boolean

Private Sub cl_MyEvent()
    On Error GoTo ErrMyEvent
    Call Err.Raise(123, , "ErrorInClass")
    m_isWorkOk = True
    Exit Sub
ErrMyEvent:
    m_isWorkOk = False
End Sub

Public Property Get IsWorkOk() As Boolean
    IsWorkOk = m_isWorkOk
End Property

这篇关于发生错误时,Goto在EventHandler子内部不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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