Что делает оператор" on Error Resume Next"?

Я пришел к некоторым примерам VBScript, и я увидел заявление On Error Resume Next в основном в начале скрипта.

что он делает?

7 ответов


Он в основном сообщает программе, Когда вы сталкиваетесь с ошибкой, просто продолжайте в следующей строке.


стоит отметить, что даже при 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 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

on Error Statement-указывает, что при возникновении ошибки во время выполнения элемент управления переходит к оператору сразу после оператора. Как когда-либо объект Err был заселен.(Ошибаться.Номер, Err.Рассчитывать и т. д.)


Он включает обработку ошибок. Следующее частично из 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, это остановит скрипт, если произошла ошибка