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

Car*_*nco 60 error-handling vbscript

我来了一些VBScript示例,我On Error Resume Next在脚本的开头基本上看到了该语句.

它有什么作用?

Dav*_*vid 79

它基本上告诉程序当你遇到错误时,只需继续下一行.


Tmd*_*ean 39

值得注意的是,即使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
Run Code Online (Sandbox Code Playgroud)


Pie*_*ant 24

发生错误时,执行将在下一行继续,而不会中断脚本.


t0m*_*13b 12

这意味着,当线路上发生错误时,它告诉vbscript继续执行而不中止脚本.有时,On Error跟随Goto标签来改变执行流程,在Sub代码块中就是这样,现在你知道为什么以及如何使用GOTO可以导致意大利面条代码:

Sub MySubRoutine()
   On Error Goto ErrorHandler

   REM VB code...

   REM More VB Code...

Exit_MySubRoutine:

   REM Disable the Error Handler!

   On Error Goto 0

   REM Leave....
   Exit Sub

ErrorHandler:

   REM Do something about the Error

   Goto Exit_MySubRoutine
End Sub

  • VBScript不支持`On Error Goto Label`语法,只支持`On Error Goto 0`. (11认同)

alf*_*edo 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.
Run Code Online (Sandbox Code Playgroud)