我看到一些VBScript示例,并且在脚本的开头看到语句On Error Resume Next
。
它是用来做什么的?
我看到一些VBScript示例,并且在脚本的开头看到语句On Error Resume Next
。
它是用来做什么的?
这基本上告诉程序,当你遇到一个错误时只需继续执行下一行。
值得注意的是,即使启用了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
当出现错误时,执行将在下一行继续进行而不会中断脚本。
这意味着,当代码出现错误时,它告诉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
On Error Goto Label
Ķ»Łµ│Ģ’╝īÕŬµö»µīüOn Error Goto 0
ŃĆé - Helen它可以实现错误处理。以下内容部分来自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.
On Error语句 - 指定当运行时错误发生时,控制流会转到紧接在该语句后面的语句。然而,Err对象将被填充。(Err.Number、Err.Count等)
On Error Resume Next 的意思是,在出现错误时,它将继续执行下一行代码。
例如,如果您尝试 Try 块,那么如果发生错误,脚本将停止执行。
On Error Resume Next
的意思就像是说“我认为这个应该能工作,但如果不行,就表现得像它工作了一样”,但实际上会给未来的维护者带来很多麻烦。要尽量避免使用它。 - Stavm