Export (0) Print
Expand All

Handling Errors in COM Objects

Microsoft® Windows® 2000 Scripting Guide

One issue that complicates error handling is the fact that system administration scripts typically make use of COM objects. If an error occurs with the COM object itself, VBScript will be aware of the error. However, VBScript might have no knowledge of what actually caused the error. For example, in the following script, WMI attempts to bind to a nonexistent printer named TestPrinter. Not surprisingly, this raises an error. You might expect, therefore, to be able to trap the error number and description and echo that to the screen:



On Error Resume Next
Set Test = GetObject _
    ("Winmgmts:root\cimv2:Win32_Printer.Name='TestPrinter'")
Wscript.Echo Err.Number & VbTab & Err.Description

When the script runs, however, you get neither a standard four-digit VBScript error number nor any error description. Instead, you get the cryptic message box shown in Figure 2.23.

Figure 2.23 COM Object Error Number and Description

sas_vbs_23s

The problem is that the error occurred within WMI, and the error details are not available to VBScript. VBScript receives notice that an error occurred, and in most scripts that type of notice might be sufficient. In other scripts, however, or when you are developing and debugging a new script, you might find detailed error information much more useful.

Many COM objects provide their own mechanisms for trapping error information. For example, WMI allows you to create an error object, SWbemLastError, and then retrieve the following information:

  • Method being called when the error occurred.

  • Parameter responsible for generating the error.

  • Name of the WMI provider where the error occurred.

The following script uses the SWbemLastError object to retrieve error information from within WMI and then display that information in a message box.



On Error Resume Next
Set Test = GetObject _
    ("Winmgmts:root\cimv2:Win32_Printer.Name='TestPrinter'")
Set WMI_Error = CreateObject("WbemScripting.SwbemLastError")
Wscript.Echo WMI_Error.Operation & VbTab & _
    WMI_Error.ParameterInfo & VbTab & WMI_Error.ProviderName

When the preceding script runs, the message box in Figure 2.24 appears.

Figure 2.24 Message Box Using SWbemLastError

sas_vbs_24s

When working with SWbemLastError, you must create the error object following the line of code where you believe an error could occur. For example, the following script will not return any error information because the SWbemLastError object was created before the error occurred:



On Error Resume Next
Set WMI_Error = CreateObject("WbemScripting.SwbemLastError")
Set Test = GetObject _
    ("Winmgmts:root\cimv2:Win32_Printer.Name='TestPrinter'")
Wscript.Echo WMI_Error.Operation & VbTab & _
    WMI_Error.ParameterInfo & VbTab & WMI_Error.ProviderName

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