“On Error Resume Next”语句的作用是什么?

70

我看到一些VBScript示例,并且在脚本的开头看到语句On Error Resume Next

它是用来做什么的?


7
这是一种非常强大但危险的语法结构。在使用时要非常谨慎。 - Nate
3
现在更有意义了。在一些可能会出现错误的函数之后,它们会调用一个名为checkError的函数来检查错误。 - Carlos Blanco
6
是的,现在已经是2018年了,但是这个仍然有效 - On Error Resume Next 的意思就像是说“我认为这个应该能工作,但如果不行,就表现得像它工作了一样”,但实际上会给未来的维护者带来很多麻烦。要尽量避免使用它。 - Stavm
7个回答

89

这基本上告诉程序,当你遇到一个错误时只需继续执行下一行。


47

值得注意的是,即使启用了On Error Resume Next,当出现错误时,Err对象仍会被填充,因此您仍然可以进行C风格的错误处理。

On Error Resume Next

DangerousOperationThatCouldCauseErrors

If Err Then
    WScript.StdErr.WriteLine "error " & Err.Number
    WScript.Quit 1
End If

On Error GoTo 0

24

当出现错误时,执行将在下一行继续进行而不会中断脚本。


11

这意味着,当代码出现错误时,它告诉VBScript在不中止脚本的情况下继续执行。有时,On Error后面会跟随Goto标签以改变执行流程,在一个Sub代码块中可能像这样使用,现在你了解了为什么和如何使用GOTO会导致代码结构紊乱:

Sub MySubRoutine()
   On Error Goto ErrorHandler

   REM VB 代码...
REM 更多 VB 代码...
Exit_MySubRoutine:
REM 禁用错误处理程序!
On Error Goto 0
REM 退出.... Exit Sub
ErrorHandler:
REM 处理错误
Goto Exit_MySubRoutine End Sub

15
VBScriptõĖŹµö»µīüOn Error Goto LabelĶ»Łµ│Ģ’╝īÕŬµö»µīüOn Error Goto 0ŃĆé - Helen

5

它可以实现错误处理。以下内容部分来自https://msdn.microsoft.com/en-us/library/5hsw66as.aspx

' Enable error handling. When a run-time error occurs, control goes to the statement 
' immediately following the statement where the error occurred, and execution
' continues from that point.
On Error Resume Next

SomeCodeHere

If Err.Number = 0 Then
    WScript.Echo "No Error in SomeCodeHere."
Else
  WScript.Echo "Error in SomeCodeHere: " & Err.Number & ", " & Err.Source & ", " & Err.Description
  ' Clear the error or you'll see it again when you test Err.Number
  Err.Clear
End If

SomeMoreCodeHere

If Err.Number <> 0 Then
  WScript.Echo "Error in SomeMoreCodeHere:" & Err.Number & ", " & Err.Source & ", " & Err.Description
  ' Clear the error or you'll see it again when you test Err.Number
  Err.Clear
End If

' Disables enabled error handler in the current procedure and resets it to Nothing.
On Error Goto 0

' There are also `On Error Goto -1`, which disables the enabled exception in the current 
' procedure and resets it to Nothing, and `On Error Goto line`, 
' which enables the error-handling routine that starts at the line specified in the 
' required line argument. The line argument is any line label or line number. If a run-time 
' error occurs, control branches to the specified line, making the error handler active. 
' The specified line must be in the same procedure as the On Error statement, 
' or a compile-time error will occur.

3

On Error语句 - 指定当运行时错误发生时,控制流会转到紧接在该语句后面的语句。然而,Err对象将被填充。(Err.Number、Err.Count等)


0

On Error Resume Next 的意思是,在出现错误时,它将继续执行下一行代码。

例如,如果您尝试 Try 块,那么如果发生错误,脚本将停止执行。


在VBA(Excel 2016)和VBScript中,使用Try/catch对我没有用。 - user2415376

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接