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

我来到了一些VBScript的例子,我在脚本的开始部分看到了On Error Resume Next语句。

它有什么作用?

它基本上告诉程序当你遇到一个错误只是继续在下一行。

值得注意的是,即使On Error Resume Next有效,Err对象仍然在发生错误时被填充,所以仍然可以执行C风格的error handling。

 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标签来改变执行stream程,类似于Sub代码块,现在您知道为什么以及如何使用GOTO可以产生意大利面代码:

 Sub MySubRoutine()
   在错误转到ErrorHandler

    REM VB代码...

    REM更多VB代码...

 Exit_MySubRoutine:

    REM禁用error handling程序!

   在错误转到0

    REM离开....
   退出小组

的ErrorHandler:

    REM做一些关于错误的事情

   转到Exit_MySubRoutine
结束小组

On Error Statement – 指定当发生运行时错误时,控制权转到语句后面的语句。 Err对象如何填充(Err.Number,Err.Count等)

它使error handling。 以下部分来自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 Resume Next表示错误,它将恢复到下一行继续。

例如,如果您尝试使用Try块,则会在发生错误时停止脚本