Introducing Error Handling
Microsoft® Windows® 2000 Scripting Guide
VBScript provides a relatively simple method for handling run-time errors within a script. Run-time errors represent any errors that are not caught by the compiler and thus manifest themselves only after the script has started running. For example, the following script generates a syntax error because the command Wscript.Echo is mistyped and the compiler is unable to interpret the line. Before a script actually runs, the scripting engine reads each line to verify that the syntax is correct; no lines of code are actually run until this checking verifies that the syntax of all the lines of code is correct. Because of that, an error message will be displayed, even though the misspelled command does not occur until line 3 in the script:
Wscript.Echo "Line 1."
Wscript.Echo "Line 2."
W script.Echo "Line 3."
Instead of the message boxes for lines 1 and 2, the error message shown in Figure 2.20 appears. This error is generated because line 3 appears to reference an invalid command named W.
Figure 2.20 Syntax Error Message
By contrast, the following script will display two message boxes before encountering an error (the misspelling of Wscript.Echo). This is because, as far as the compiler is concerned, line 3 is typed correctly. The compiler has no way of knowing that Eho is not a valid Wscript property and thus does not flag this as an error. VBScript cannot determine the properties and methods of a COM object in advance (that is, before a particular line of code runs).
Wscript.Echo "Line 1."
Wscript.Echo "Line 2."
Wscript.Eho "Line 3."
When line 3 of the script is actually run, the error message shown in Figure 2.21 appears. You might notice that this error message lists the source as a Microsoft VBScript run-time error rather than as a compilation error.
Figure 2.21 Runtime Error Message
Not all run-time errors involve typographical errors within the script. For example, this line of code is syntactically and typographically correct. However, it will also generate a run-time error if the remote computer named InaccessibleComputer is not available over the network:
Set Computer = GetObject("winmgmts:\\InaccessibleComputer")
This means that run-time errors are bound to occur, if only because of activities beyond your control. (The network goes down, a computer is shut down, another administrator deletes a user account.) With VBScript, you have three options for handling errors. The advantages and disadvantages of each of these options are summarized in Table 2.19.
Table 2.19 Advantages and Disadvantages of Error Handling Options
Option |
Advantages |
Disadvantages |
---|---|---|
Allow the script to fail. |
|
|
Have the script ignore all errors. |
|
|
Write code to respond to errors as they occur. |
|
|