VbScript With Error Handling

Embed Size (px)

Citation preview

  • 8/4/2019 VbScript With Error Handling

    1/4

    VBScripting- Runtime Error Handling:::::

    http://msdn.microsoft.com/en-us/library/xe43cc8d(VS.85).aspx

    VbScript with error handling

    Ever thought about how to handle unexpected runtime errors in your VBScripts? Its so cool when everyting works like you

    expect it to, but what if something goes wrong?

    You are the person in charge of the network and you make a VBScript that maps a printer to the users computers each time the

    person logs on the network. For instance with the following code:

    Option Explicit

    Dim strPrinterUNC, objNetwork

    strPrinterUNC = "\\serverName\printerShareName"

    Set objNetwork = CreateObject("WScript.Network")

    objNetwork.AddWindowsPrinterConnection strPrinterUNC

    objNetwork.SetDefaultPrinter strPrinterUNC

    This might work, but what if the printer has an error or the server the printer is attached to is down?

    Your users might receive an annoying error like on the picture below and may start to wonder whether you are actually the

    right person for the job.

    Of course its not necessarily your fault that the printer is not online, but such errors typically cause the users who dont

    bother a lot about IT to think that the world is falling apart and we dont want our users to think so. We want them to be

    relaxed and have them go and make them self a cop of coffee while they wait for the printer to be back online.

    The above script can easely be amended a bit to come up with a lot friendlier error message if the printer is not available.

    On Error Resume Next

    objNetwork.AddWindowsPrinterConnection strPrinterUNC

    objNetwork.SetDefaultPrinter strPrinterUNC

    If Err.Number 0 Then

    MsgBox "An error occured during mapping of the default printer: " & Err.Description

    End IfOn Error GoTo 0

    This is still the same script in terms of mapping the printer, but now we have specified that we want the script to continue

    even if it runs into an error.

    We have done so by writing On Error Resume Next before the code we expect can fail.

    Furthermore we have put an If condition that will be triggered in case of an error, that is if Err.Number differs from 0, wich is

    the default number returned if the script runs without problems and everything goes as we expect (i.e. hope for).

    Finally we have the On Error GoTo 0, which tells the script to stop the error handling and continue without error handling

    throughout the remaining of the script.

    http://msdn.microsoft.com/en-us/library/xe43cc8d(VS.85).aspxhttp://msdn.microsoft.com/en-us/library/xe43cc8d(VS.85).aspx
  • 8/4/2019 VbScript With Error Handling

    2/4

    Now, if the printer is unavailable and we have taken the effort to write our own error message, we will receive an error like:

    It looks a little cleaner and may cause less confusion for the users on your network.

    Its possible to write your own comments about the error and mix it with the actual error description returned from the script

    host.

    This is done by using the Err.Description as shown in the previous script snippet.

    You can also use Err.Number if you want to return the error code and work with this to return different messages to the users

    depending of the specific error number.

    Something like:

    If Err.Number = xxx Then

    Do something smart here

    Else If Err.Number = yyy Then

    Do something even smarter here

    End If

    Error handling in VBS is limited to two On Error ... statements: (1) OnError Resume Next, which initiates runtime error trapping and continues tothe next statement, if an error occurs; and (2) On Error Goto 0, thestandard state, which exposes runtime errors and terminates the code. Onlyruntime, not syntax, errors will be trapped, although VBS handles manysyntax-like errors at runtime (e.g., mistyped variable and function names)that can be masked by error-trapping.

    The Err object appears to be somewhat incorrectly documented in the MS VBS

    documentation. That documentation indicates that the On Error Resume Nextstatement, but not the On Error Goto 0 statement, will implicitly clear(reset) any error data; and that Exit ... and End ... procedure statementswill implicitly clear (reset) any error settings. In fact, VBS handlesadditional error object instances or settings in a scope-sensitive manner;both of the On Error ... statements will implicitly clear (reset) any errordata; and Exit ... and End ... procedure statements do not implicitly clear(reset) any error settings.

    The Err object is an intrinsic global object available under all hosts.When an error occurs, VBS will start with the present procedure, if any,and, if no error-trapping is presently in force in the procedure, will thenlook back along the call stack to the global script, to ascertain whetherthere is error-trapping status in effect at any level in the stack. If itfinds one, it will jump to the next statement at that level (potentiallyafter the call to the error-producing procedure or one of its parentprocedures). If not, VBS displays a runtime error message and terminates.

    The Err object has two intrinsic methods: (1) Clear, which expressly clearsthe Err object properties and resets them, as if no error has occurred, and(2) Raise, which simulates a runtime error. Both of the On Error ...statements will implicitly clear (reset) the Err object properties. Ifexiting a procedure after a trapped error, without first executing anErr.Clear statement or proceeding through an On Error Goto 0 statement, thestatus of the Err object properties will be maintained, and any conditionalstatement in the script back along the call stack relying on that status(e.g., if err then ... ) will be implemented, regardless of whethererror-trapping status is presently in force in that code.

    The Err object has two particularly significant properties: (1) Number,

  • 8/4/2019 VbScript With Error Handling

    3/4

    which returns zero, if no error has been registered or if an error has beencleared (reset), or a non-zero long integer error code, indicating the errorthat has been registered; and (2) Description, which is a text descriptionof the error. Number is the default property and can be omitted inassignment or condition statements (e.g., cErr= err or if err then ... ).While the error code number is usually sufficient to identify an error, text

    descriptions are occasionally different for different errors represented bythe same error code, so resort to the text of the description may sometimesalso be necessary, to better resolve the nature of the error.

    Invocation of error-trapping through On Error Resume Next in prior script inthe calling stack does not extend into a called procedure's scope. Thispermits a script to place a generic error handler earlier in the callingstack, while still using specific error handlers in the later procedures.

    Unless one has well-crafted and specific plan for catch-all error handlingin a script of limited scope, however, it is usually best to set local errorhandling only, and for as narrow a range as feasible, to avoid masking

    routine errors that can be corrected, as well as unforeseen errors that willbe mistaken for a different type of error.

    VBS error handling lacks call stack tracing, but that aspect can be added

    with privately implemented procedures or classes. Similarly, VBS errorhandling lacks the ability to jump to different line numbers on errors.That ability can be partially simulated, where necessary, through proceduredesign and the implementation of script arguments that call those proceduresin different order, where the script reruns itself with the appropriateargument and quits, when a specific error is encountered.

    One special area of error handling involves the use of With blocks. A Withblock must always be literally exited, by allowing operation to proceedthrough the End With statement. As the MS WSH documentation makes clear,you cannot exit a With by simply terminating the script or through any ofthe standard block exits, without risking "memory leaks" and/or some verypeculiar errors, including some unenlightening error messages generated whenthe script tries to quit. So it may be necessary to use one or morefaux-loops inside a With block, to exit to the End With statement, prior toacting on the error.

    Error Handling Rules Overview

    VBScript offers some limited facilities to help your manage runtime errors. Here is a summary of rules that will help youto properly manage runtime errors in your VBScript code:

    1. The "On Error Resume Next" statement can be used to turn on the error handling flag.

    2. The "On Error GoTo 0" statement can be used to turn off the error handling flag.

    3. User defined procedures have their own error handling flags. This means that each user defined procedure should be

    have its own "On Error Resume Next" or "On Error GoTo 0" statement to turn on or off its own error handling flag.

    4. By default, error handling flags of all user defined procedures and the main code are turned off.

    5. By default, the host environment provides a built-in object called "Err" to hold runtime error information.

    6. When a runtime error occurs, the host environment will set values to properties of the "Err" object and raise a runtime

    error.

    7. When a runtime error is raised and the current error handling flag is on, the host environment will continue to execute

    the next statement.

    8. With the error handling flag turned on, you can inspect "Err" object properties to determine how to handle the error

    and continue your code execution.

  • 8/4/2019 VbScript With Error Handling

    4/4

    9. When a runtime error is raised in a procedure and the current error handling flag is off, the host environment will stop

    executing the procedure, transfer execution control to the calling code, and raise the same runtime error in the calling

    code.

    10. When a runtime error is raised in the main code and the current error handling flag is off, the host environment will

    stop executing the main code, and take some additional steps.

    11. When Internet Explorer (IE) gets a runtime error with the error handling flag turned off, it will display small dialogbox, if its script debug option is turned on.

    12. When Windows Script Host (WSH) gets a runtime error with the error handling flag turned off, it will print out an

    error message.

    Conclusions:

    Runtime errors will be managed by the host environment, if you don't manage them.

    "On Error Resume Next" turns on the error handling flag, which causes the host environment to continue

    executing the next statement after raising a runtime error.

    "On Error GoTo 0" turns off the error handling flag, which causes the host environment to stop executing the

    current procedure after raising a runtime error.

    The "Err" object is built-in object representing the last runtime error.

    "Err.Number > 0" can be used to see if a runtime error has occurred or not.

    "Err.Clear()" method can be used to clear the "Err" object.

    "Err.Raise()" method can be used to raise your own runtime errors.