On Error - VBScript
Overview
The On Error
command in VB Script enables customized error handling, allowing you to define how the script responds to errors. By intercepting errors, you can gracefully handle them or redirect the script’s execution path to provide better user feedback or maintain script continuity.
Syntax
Option Explicit
On Error [Resume | Resume Next]
On Error Goto [label]
Options/Flags
- Resume: Resumes script execution from the line following the error-generating line.
- Resume Next: Same as Resume, but only resumes execution of the next statement after the error-generating line.
- [label]: An optional user-defined label that specifies the line where the script should jump to after an error occurs.
Examples
Simple Error Handling
On Error Resume Next
DoSomethingRisky()
' Continue execution even if DoSomethingRisky() fails.
Jumping to a Specific Label
On Error Goto HandleError
DoSomethingRisky()
Exit Sub
HandleError:
' Error handling code goes here.
Error Object
On Error Resume Next
DoSomethingRisky()
If Err <> 0 Then
' Error occurred, handle it using the Err object.
End If
Common Issues
Skipping Error Checking
Forgetting to check for errors using If Err <> 0
after using On Error Resume Next
can lead to unnoticed errors and unexpected outcomes.
Infinite Loops
Using On Error Resume Next
without a Goto
label can lead to infinite loops if the error continues to occur.
Integration
The On Error
command can be combined with other error handling tools, such as the Err
object and Error
function, to provide comprehensive error management.
Related Commands
Err
: Provides access to the error object.Error
: Raises an error with a specified error code and description.Exit Sub
: Exits the current subroutine.