Error Trapping and Capturing Third-Party Output in WSH - Trapping Errors
(Page 2 of 4 )
The Err object is used for every error that occurs. Each time you read its value, you must clear it before moving on with the Clear method. You may also choose to create your own errors in some circumstances. You can do that with the Raise method.
The Err object is initialized by the VBScript Engine every time a script is executed. You do not need to instantiate it in your code to use it.
A basic If routine is all you need for an error check. You’re simply going to query the Err number property to see if it’s anything other than 0. Try this for example:
If Err.Number <> 0 Then
Wscript.Echo "Error: " & Err.Number
Wscript.Echo "Description: " & Err.Description
Wscript.Echo "Source: " & Err.Source
Err.Clear
End If
This is a simple error-check. We can use this same code to write to a log file instead. The key here to is remember to clear the error object to prevent it from combining multiple errors.
At times it may be useful to flag errors while using your own error-handling method. Let’s say your code is designed to respond to a certain error. In that case we can still use the Err object for logging purposes.
Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists("nosuch.file") Then
Err.Raise 53,, "Cannot find specified file"
Call errChk
objFso.CreateTextFile("nosuch.file")
End If
Sub errChk
If Err.number <> 0 Then
Wscript.Echo "Error: " & Err.Number
Wscript.Echo "Description: " & Err.Description
Wscript.Echo "Source: " & Err.Source
Err.Clear
End If
End Sub
Here we’ve manually raised an Error 53 which is a File Not Found error. Our script is set to handle this by creating the file that doesn’t exist but our error handler still gets a chance to log it if we so choose.
So why did we have to create the error? The answer is simple; because the FileExists method returns an error code of 0. The method was able to complete successfully.
Next: Logging to the Event Log >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer