Export (0) Print
Expand All

Toggling Error Handling

Microsoft® Windows® 2000 Scripting Guide

At times you might want to implement error handling in one portion of a script but not in another portion. In other words, sometimes you might want to trap errors, while other times you might prefer to simply let the script fail.

You can toggle error handling on and off by:

  • Using the On Error Resume Next statement to turn error handling on.

  • Using the On Error GoTo 0 statement to turn error handling off. After this statement has been run, error handling will not take place until another On Error Resume Next statement has been encountered.

For example, in the following script, error handling is implemented in the first line. In the second line, an error occurs because Wscript.Echo has been misspelled. However, because error handling has been implemented, the script will continue to run. Error handling is turned off in line 3, using On Error GoTo 0, and then reimplemented in line 5. Because no errors occur while error handling is off, the script will run without failing.



On Error Resume Next
Wscript.Eco "A"
On Error GoTo 0
Wscript.Echo "B"
On Error Resume Next
Wscript.Eco "C"
Wscript.Echo "D"

When the preceding script is run under Cscript, the following data is displayed in the command window. The values "B" and "D" are the only values echoed to the screen because those are the only lines of code that could be run without generating an error.



B
D

The following sample script shows a slightly revised version of the same script. In this case, error handling is turned on and then off, but this time an error occurs while error handling is off.



On Error Resume Next
Wscript.Eco "A"
On Error GoTo 0
Wscript.Eco "B"
On Error Resume Next
Wscript.Eco "C"
Wscript.Echo "D"

When this script is run under Cscript, the following error message is displayed in the command window:



C:\Documents and Settings\gstemp\Desktop\Scripts\x.vbs(4, 1) Microsoft VBScript
runtime error: Object doesn't support this property or method: 'Wscript.Eco'

In this case, the script fails to run line 2 (with the misspelling of Wscript.Echo) but continues to run because error handling has been implemented. In line 3, however, error handling been turned off. As a result, the misspelling in line 4 causes the script to fail, generating a run-time error and the resultant error message.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft