且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么你会使用“On Error Goto 0”?

更新时间:2023-02-19 22:23:21

在VB6中,您可以指定要在稍后的特定代码中处理错误例程:

 子栏()
错误转到MyHandler
...
...一些代码抛出一个错误...
...
退出Sub
MyHandler:
...一些错误处理程序代码(可能弹出一个对话框)
End Sub

可能是这样,抛出错误的代码是本地化,并且您不希望该程序中所有其他代码的同一个处理程序。在这种情况下,您将使用On Error Goto 0,如下所示:

 子栏()
。 ..
错误Goto MyHandler
...一些代码引发错误...
错误Goto 0
...
...
退出Sub
MyHandler:
...一些错误处理程序代码(可能弹出一个对话框)
End Sub

现在,您已经有效地限定了错误处理,只有在特定的代码行失败时才执行。



通过调用 On Error Goto 0你不是说你想让应用程序立即崩溃。您只是想要在程序中更早地设置的任何错误处理程序进行注销;错误将被传递给调用堆栈到调用例程,如正常。


Why would you ever use "On Error Goto 0" in a VB6 app?

This statement turns the error handler off and would mean that any error would crash the app. Why would this ever be desirable?

In VB6, you can specify that you want errors to be handled by particular code later in the routine:

Sub Bar()
    On Error Goto MyHandler
    ...
    ...some code that throws an error...
    ...
    Exit Sub
MyHandler:
    ...some error handler code (maybe pops up a dialog)
End Sub

It may be the case, however, that the code that throws the error is localized, and you don't want that same handler for all of the rest of the code in the routine. In that case, you'd use "On Error Goto 0" as follows:

Sub Bar()
    ...
    On Error Goto MyHandler
    ...some code that throws an error...
    On Error Goto 0
    ...
    ...
    Exit Sub
MyHandler:
    ...some error handler code (maybe pops up a dialog)
End Sub

Now you have effectively scoped the error handling to execute only if that particular line of code fails.

By calling "On Error Goto 0" you are NOT saying that you want the app to crash immediately. You are simply saying that you want to de-register any error handlers that you may have set up earlier in the routine; errors will be passed up the call stack to calling routines, like normal.