Handling Errors
A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next
. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear
below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:
On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
WScript.Echo "Error: " & Err.Number
WScript.Echo "Error (Hex): " & Hex(Err.Number)
WScript.Echo "Source: " & Err.Source
WScript.Echo "Description: " & Err.Description
Err.Clear ' Clear the Error
End If
On Error Goto 0 ' Don't resume on Error
WScript.Echo "This text will always print."
Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear
with WScript.Quit(Err.Number)
.
Also note the On Error Goto 0
which turns off resuming execution at the next statement when an error occurs.
If you want to test behavior for when the Set
succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp
.
The On Error
directive only affects the current running scope (current Sub
or Function
) and does not affect calling or called scopes.
Raising Errors
If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise
. Err.Raise
takes up to five arguments, Number
, Source
, Description
, HelpFile
, and HelpContext
. Using help files and contexts is beyond the scope of this text. Number
is an error number you choose, Source
is the name of your application/class/object/property that is raising the error, and Description
is a short description of the error that occurred.
If MyValue <> 42 Then
Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If
You could then handle the raised error as discussed above.
Change Log
Edit #1:
Added an Err.Clear
before the possibly error causing line to clear any previous errors that may have been ignored.
Edit #2:
Clarified.
Edit #3:
Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next
and Err.Clear
. Fixed some grammar to be less awkward. Added info on Err.Raise
. Formatting.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…