Search code examples
vbscripterror-handling

VBScript -- Using error handling


I want to use VBScript to catch errors and log them (ie on error "log something") then resume the next line of the script.

For example,

On Error Resume Next
'Do Step 1
'Do Step 2
'Do Step 3

When an error occurs on step 1, I want it to log that error (or perform other custom functions with it) then resume at step 2. Is this possible? and how can I implement it?

EDIT: Can I do something like this?

On Error Resume myErrCatch
'Do step 1
'Do step 2
'Do step 3

myErrCatch:
'log error
Resume Next

Solution

  • VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.

    On Error Resume Next
    
    DoStep1
    
    If Err.Number <> 0 Then
      WScript.Echo "Error in DoStep1: " & Err.Description
      Err.Clear
    End If
    
    DoStep2
    
    If Err.Number <> 0 Then
      WScript.Echo "Error in DoStop2:" & Err.Description
      Err.Clear
    End If
    
    'If you no longer want to continue following an error after that block's completed,
    'call this.
    On Error Goto 0
    

    The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.