On Error Statement
- Updated2024-09-12
- 2 minute(s) read
VBScript Language Directory > On Error Statement
On Error Statement
Runtime errors occur when the script engine attempts to execute an invalid statement, for example, when the script divides by zero or tries to access a non-existent file. How you react to a runtime error depends on the type of error, its cause, and its consequences. In some cases, you only need to display an error message and stop the script.
The easiest way to react to errors is to ignore them using the On Error Resume Next statement. If an error occurs – On Error – , the error is skipped when Resume Next executes. This means that the script continues with the statement subsequent to the statement that caused the error.
The On Error statement only applies for the procedure in the statement, not globally.
Therefore, you must set the On Error Resume Next statement, as shown in the next example, before the line that can cause an error:
Dim rVal On Error Resume Next rVal = 12/0 Call MsgBox(rVal)
The error is ignored and the script continues with the next statement. An empty message box appears.
If you ignore the error and an error occurs in an If statement, DIAdem executes the statement that follows End If. If an error occurs in a For statement, DIAdem executes the statements once in the For...Next loop.
If you enable error handling with On Error Resume Next, use the On Error Goto 0 statement to end error handling:
Dim rVal On Error Resume Next rVal = 12/0 If (Err.Number <> 0) Then Call MsgBox(Err.Description) Call MsgBox(Err.Number) Call MsgBox(Err.Source) End If On Error Goto 0
However, errors may also affect other parts of the script, so ignoring errors is not recommended. It is better to detect and handle errors.
Use the integrated Err object for global error handling. The Err object contains information about the last error that occurred. The object includes the methods Raise and Clear, for triggering and deleting runtime errors. The object properties include the Number, the Description, and the Source of the error.
Related Topics
On Error | Err