Chapter 10

Error Handling

by Craig Eddy


CONTENTS

It seems no matter how hard you try to avoid them, errors are inevitable in any program. Even if your application is coded perfectly, those pesky users always will discover some idiosyncrasy in the application that you never even dreamed possible. Fortunately, because your VBScript applications typically are hosted by the Internet Explorer, the system damage that errors (user- or code-induced) can cause is minimal.

On the other hand, an error that occurs within a VBScript page more than likely will cause the entire page to malfunction. This is akin to an untrapped runtime error in a Visual Basic application. In this case, the user sees a message box describing (to some extent) the error that occurred, and then the user is summarily thrown out of the application. In a VBScript Web page, if an untrapped error occurs, a similar message box is presented to the user.

Although it's impossible to eliminate every error, this chapter describes some methods for coding your VBScript applications that should help avoid most coding errors. It also covers that extremely important part of coding: error handling. In the "Looking at Examples of Error Handling" section later in this chapter, you'll learn how to trap runtime errors in your scripts. The chapter concludes with some scripts that provide examples of error handling.

Because error handling and debugging go hand in hand, you will see some overlap with Chapter 12, "Debugging." Although both chapters look at error handling, they explore different approaches. This chapter emphasizes error handling exclusively, while Chapter 12 looks at error handling as a component of the larger debugging problem.

Handling Errors in Your VBScript Pages

When your VBScript code runs within the Internet Explorer, you can be pretty certain that errors won't have a grievous effect on the user's system. Internet Explorer and the current limits within VBScript code confine the damage your code can do to the user's computer.

The same might not be true, however, of ActiveX components you might use within your Web pages. Because users have to retrieve any ActiveX controls used on your pages, you must ensure that you're using these controls properly. Also, you should feel good about the controls themselves-that they don't contain viruses and that they can't harm your users' systems in any way. As a Web page designer, you have a responsibility to those who will be viewing your pages to make sure that no damage can be done to their systems or to the files on their systems.

This section looks at some of the possible errors that might crop up within your VBScript code. It discusses syntax errors, errors with ActiveX controls, and general runtime errors. The next section, "Coding to Avoid Errors," presents ways to avoid these common errors.

Syntax Errors

Unlike the Visual Basic development environment, there is no syntax checker for VBScript code. If you enter your VBScript code using Notepad or the Microsoft ActiveX Control Pad, you'll have to make sure that there are no syntax errors within your script code. You also can use the Visual Basic development environment to enter your script code and then cut and paste it into your HTML pages. This might be preferable if you have a lot of code, but usually is more trouble than it's worth.

If syntax errors are present within your scripts, Internet Explorer displays a syntax error dialog, such as the one shown in Figure 10.1.

Figure 10.1 : A syntax error displayed in Internet Explorer.

You can specify whether other errors in the script should be ignored by enabling the Ignore further script errors on this page checkbox at the bottom of the dialog. By disabling the checkbox, you're informing the script compiler that it should continue parsing the script code and inform you of additional errors. In the version of Internet Explorer I had at the time of this writing (IE 3.0 beta 2), however, this feature did not seem to work.

Typical syntax errors include misspellings and combining two words into one, such as "endif" instead of "end if." I run into this one all the time, because I'm used to Visual Basic replacing my typing of "endif" with the correct "end if." The easy way around this error is to run a search-and-replace operation before saving your code.

You also can cause syntax errors by misplacing or mismatching operators within an expression. For example, the code


MsgBox "Hello " & txtName.Text &

causes a syntax error, because the VBScript compiler is expecting something to follow the last ampersand.

WARNING
Because the VBScript compiler ignores white space (such as space characters and carriage returns), a syntax error generated by "hanging" operators is flagged on the line following the offending line.

Another common source of syntax errors is leaving the Then off of an If...Then expression. This typically is done by those of us who also code SQL Server Transact-SQL procedures, which don't use Then. This particular syntax error also is flagged on the line following the If, but the dialog at least tells you that the Then is missing.

Errors with ActiveX Controls

VBScript lets you embed ActiveX (formerly OLE) controls within your Web pages. These ActiveX controls operate just like custom controls in Visual Basic applications: They have properties that can be set, methods that can be invoked, and events that can fire based on user interaction within your page. Because you have programmatic access to all these features within your VBScript code, you also have the potential to cause a lot of errors if you use the controls improperly. This section discusses a few possible errors to watch out for.

The most common error results from incorrectly coding the <OBJECT> HTML tag used to insert an ActiveX control into the Web page. Because this tag contains many of its own elements, such as CODEBASE and ID, along with elements for the properties of the ActiveX control, it is very easy to mistype a setting or leave an important setting off all together.

The <OBJECT> tag also requires that you specify the globally unique class identifier for the control in the CLASSID element. The globally unique identifier (GUID) is a unique alphanumeric string assigned to OLE controls when they are created. It not only identifies the control but also makes sure that the correct version of the control is being used. A typical GUID looks like this:


0BA686AA-f7D3-101A-993E-0000C0Ef6f5E

This string must be entered for each ActiveX control you place on your Web page. Of course, if you mistype any character within the class ID, you're not going to get the ActiveX control you intended. Fortunately, the ActiveX Control Pad, discussed in the next section, inserts the GUID and control properties into your HTML code for you.

It also is possible to create runtime errors when using ActiveX controls. This happens when you assign an invalid value to a control property, for example. When using an ActiveX control within your VBScript code, make sure that you understand the properties and methods you're using. This helps you avoid many common runtime errors. Fortunately, most controls you'll use are published by commercial software vendors who almost always provide adequate documentation.

Runtime Errors

Unlike syntax errors, runtime errors do not occur until your VBScript code executes. These errors, unless they are trapped by your code, cause the script to halt after the error dialog appears.

Runtime errors can result not only from mistakes within your code but also from user interaction. The most common cause of this occurs when using data the user has entered into a control on the Web page. If you have a standard text box for entry of a numeric value, for example, the user may enter any alphanumeric character. If you then attempt to use this value as-is with a function or procedure that expects a numeric parameter, a runtime error results.

The section "Coding to Handle Errors," later in this chapter, discusses how to write your VBScript code to properly handle runtime errors.

Coding to Avoid Errors

Although it is nearly impossible to avoid all runtime errors, there are some steps you can take when writing VBScript code to minimize the number that slip through the cracks. This section highlights a few of the pointers I've uncovered while creating scripts.

The famous Save Often commandment is missing, however, because you currently always have to save the HTML pages containing VBScript before you can open them in Internet Explorer. Hopefully, Microsoft will soon release a version of Internet Explorer that enables you to edit and debug VBScript code. VBScript code editing is planned for the Internet Studio, but I'm not aware of that product including any debugging tools.

Using the ActiveX Control Pad

For the moment, the best tool available for coding VBScript applications is Microsoft's ActiveX Control Pad. You can download this tool from Microsoft's SiteBuilder Web site. At the time of this writing, the URL for the download page is


http://www.microsoft.com/workshop/author/cpad/download.htm

If you haven't already downloaded this tool, I highly recommend doing so.

This section discusses a few of the features of the Control Pad and illustrates how these features help you avoid many of the common VBScript coding errors. The Control Pad is covered in depth in Chapter 8 "The ActiveX Control Pad." Here I cover it only enough for a demonstration of error handling. Read Chapter 8 for complete coverage of the Control Pad.

Examining the ActiveX Control Pad

The ActiveX Control Pad has been jokingly referred to as Visual N++ or Visual Notepad, because it strongly resembles the Notepad application, but with a toolbar and a few extra visual elements. Figure 10.2 shows the initial screen of the Control Pad. Although it might resemble Notepad on the surface, it has a lot of power under the hood.

Figure 10.2 : The ActiveX Control Pad's opening screen.

As you can see in Figure 10.2, when the Control Pad starts a new HTML file, it already has entered the standard HTML wrapper codes. This enables you to quickly start creating the HTML and VBScript code specific to the page you are creating.

The Control Pad functions just like Notepad. You can type in the open window, use the text-editing features (Cut, Copy, and Paste), print the file, and save and open other files. Unlike Notepad, the Control Pad sports a toolbar and a multiple document interface that enables you to open multiple HTML files at the same time.

Using ActiveX Controls

The most useful feature of the Control Pad is its capability to insert all the necessary HTML code for an ActiveX control. You even can edit the properties of a specific control that has been inserted into your page, by using an interface similar to the Visual Basic Properties dialog.

To insert an ActiveX control onto your page, follow these steps:

  1. Position the cursor at the point where you want to insert the control.
  2. Choose Edit | Insert ActiveX Control. The Insert ActiveX Control dialog appears.
  3. Select the desired control in the Control Type list and click the OK button. Two windows appear: the Edit ActiveX Control window and the Properties window. (See Figure 10.3.)
    Figure 10.3 : Editing ActiveX controls in the Control Pad.

  4. Use the Edit ActiveX Control window to size the control. Use the Properties window to edit any other properties as necessary. The Properties window provides popup dialogs for font and color properties, as well as drop-down listboxes for enumerated properties such as Alignment.
  5. After you finish editing the control, close the two windows by clicking their Close buttons (the box with the X at the right of the title bar). The HTML code matching the control and its properties is inserted into the page, as shown in Figure 10.4.
    Figure 10.4 : HTML code for an ActiveX control.

After you insert the control into your page, you might need to edit some of its properties. You can do this by directly modifying the text associated with the PARAM elements of the control's <OBJECT> tag. This requires that you know the proper settings for the properties you're modifying, however. Fortunately, you also can return to the Properties window by clicking the button next to the <OBJECT> tag. This button is in the left margin of the ActiveX edit window and has a picture of a cube.

A quick way to insert a copy of the same control is to select everything from the <OBJECT> tag to the </OBJECT> ending tag. Then choose Edit | Copy, place the cursor at the location for the new copy of the control, and choose Edit | Paste. Then be sure to change the ID element of the <OBJECT> tag to a unique name, because VBScript does not support control arrays.

Editing VBScript Code

The ActiveX Control Pad's script-editing features are even more powerful than its control property-editing features. The Control Pad has a Script Wizard that enables you to enter and edit code in a manner similar to code entry with Visual Basic, but with a slightly different interface, as shown in Figure 10.5.

Figure 10.5 : The ActiveX Control Pad's Script Wizard.

To open the Script Wizard, choose Tools | Script Wizard or click the Script Wizard toolbar button (the one with the picture of an unfurled scroll). The Script Wizard operates in an application modal window. This means that you cannot do anything else in the Control Pad while the Script Wizard is active.

To select which event you want to write script code for, use the tree control at the top left of the Script Wizard. Clicking the box with the plus sign (+) displays a list of the available events for the selected object. Then simply select the event of interest by clicking it.

At the top right of the window is a tree list labeled Insert Actions. This list is similar to Visual Basic's object browser, because it lists all the available controls and their properties, as well as everything available in the Internet Explorer's window object. It also lists any global variables and procedures that have been created in the page's script. To insert an item, select it in the list and double-click it.

Code is actually entered into the script at the bottom of the window. As you can see in Figure 10.6, there are two possible views for this area: List View and Code View. List View enables you to view the script in a high-level, more English-like manner. Code View is similar to Visual Basic's Code View. You'll probably use Code View more often than List View because it gives you much more flexibility in entering VBScript code.

The easiest way to learn how to use the Script Wizard is to "just do it." Enter some controls onto your page and open the Script Wizard. Select an event from the Event list, and then select Code View and enter some code for that event. Use the Insert Actions list to quickly insert references to properties and other objects.

After you insert a <SCRIPT> tag, either manually or by using the Script Wizard, a Script Wizard button appears next to it. This button appears in the left margin of the Control Pad's editor window. Clicking it takes you to the Script Wizard.

Using OptionExplicit

Probably the worst type of error to track down is the improper naming of a variable. If your fingers, like mine, tend to be dyslexic, you probably find yourself constantly swapping letters as you type. Often, I don't even notice that I've done this. When my code runs with such a mistake in it, it never seems to work quite right. It's not until I discover the misspelled variable name that the code works properly.

To avoid such problems, use the Option Explicit directive. This forces you to declare every variable used within your script code. This way, when you misspell a variable, it is flagged as an undefined variable when your script executes. Figure 10.6 shows an example of the dialog displayed.

Figure 10.6 : The Undefined Variable Error dialog.

WARNING
The Script Wizard often breaks up your scripts into several parts within the HTML page. You must have an Option Explicit directive within each <SCRIPT> ... </SCRIPT> pair. If you omit the Option Explicit directive, you may not catch a misspelled variable name in that section.

Using Coding Conventions

Another technique that can help you avoid errors is to use a coding convention. Coding conventions help you write code that is easily readable and understandable. As you'll see, they also keep you on your toes when naming and using variables.

The most important coding convention involves naming conventions for variables. The convention I tend to use is a single-character prefix that represents the data type of each variable. Microsoft, on its VBScript Web site, recommends a three-character prefix. The extra characters are necessary to uniquely identify each of the possible data types available in VBScript. I typically only use a few of these data types in my coding, so the one-character prefix is fine for me. Table 10.1 lists the Microsoft-recommended prefixes.

Table 10.1. Microsoft's recommended variable name prefixes.

Data typePrefix Example
BooleanblnblnStateResident
BytebytbytCharacter
Date/Timedtm dtmStartDate
DoubledbldblProductCost
ErrorerrerrFileError
IntegerintintQuantity
LonglnglngCount
ObjectobjobjWordDoc
SinglesngsngAverage
StringstrstrFileName

Microsoft also recommends a naming convention for naming ActiveX objects you insert into your Web pages. Table 10.2 lists these prefixes.

Table 10.2. Microsoft's recommended ActiveX object-naming prefixes.

Object typePrefix Example
3-D panelpnl pnlStatus
Animated buttonani aniStateButton
Checkboxchk chkResident
Comboboxcbo cboContactType
Command buttoncmd cmdSubmit
Common dialogdlg dlgFiles
FramefrafraGrouping
Horizontal scrollbarhsb hsbBrightness
ImageimgimgContactPicture
LabellbllblFormLabel
Listboxlst lstNames
SlidersldsldScale
SpinspnspnValue
Text boxtxt txtLastName
Vertical scrollbarvsb vsbHeight

Coding to Handle Errors

Despite the best efforts of any programmer, errors still can occur, even in flawless code. These errors can result from any number of causes. The preceding section described how to structure your VBScript code in order to avoid as many errors as possible. In this section, you learn how to handle runtime errors.

Runtime errors occur, obviously, when your script is being executed by the host application. In the case of Internet Explorer, runtime errors that aren't trapped within your script cause the Internet Explorer Script Error dialog to be displayed. Figure 10.7 provides an example of such an Error dialog.

This section describes the two VBScript features provided for handling errors in your scripts. The first section describes how you can specify the actions taken when a runtime error occurs. The second section describes the Err object, which provides information about the error that occurred. The properties and methods of the Err object are described here, including the masochistic method Raise, which enables you to create a runtime error within your script. Examples of error handling are provided in this section.

Specifying Error Trapping

In order to trap runtime errors within your script, you must inform the script host (such as Internet Explorer) that you want to do so. You do this by using the On Error statement.

The current syntax for this statement is actually a subset of the Visual Basic On Error statement. In VBScript, there is no support for any construction other than On Error Resume Next or On Error Goto 0. This means that there is no support for a centralized error-handling mechanism that typically is found in most applications. I suppose that this is because of the lack of labels within script code; you cannot specify On Error Goto ErrorLabel, for example.

To trap errors, you first specify On Error Resume Next. Then, after each line of script code for which errors are possible, you must check the value of the Err object to see whether it's greater than zero. The following snippet of script code shows an example:


On Error Resume Next

MsgBox Left("The Quick Brown Fox", intCount)

If Err > 0 Then MsgBox "Error: " + Err.Description

If the value of intCount is less than 0 when the second line is executed, an error condition occurs. If errors aren't being trapped, a message box is displayed and the script's execution ends at that point. Because the script is handling errors, however, a message box is displayed and the code continues execution.

Any error trapping becomes inactive when another procedure is called, so you should place an On Error Resume Next statement in each procedure if you want to include error trapping within that procedure.

To turn off error trapping and allow the script's host application to decide how to handle any runtime errors, use the statement On Error Goto 0. This opens your script up to the possibility that a runtime error will halt its execution, however.

Using the Err Object

When an error occurs (from a runtime error, an OLE object, or the Raise method executing), the Err object is used to interpret the cause and context of the error condition. The Err object always is available to your scripts and is global in scope.

The generator of the runtime error is responsible for setting the Err object's properties before raising the error condition. The only property required is the Number property. The other properties are optional.

This section describes the properties and methods available with the Err object.

The Err Object's Properties

The Err object has several properties that help describe the error that occurred, as well as the source of the error. This section describes those properties.

Number Property

The Number property is the default property for the Err object. This means that the following two lines of code are identical:


If Err.Number > 0 Then

If Err > 0 Then

The Number property specifies the error number assigned to the error that occurred. When you are using the Raise method to generate a runtime error, add the constant vbObjectError to your error number in the Raise method's Number parameter.

In your script, you should check the Number property (explicitly or by simply using Err) against any known error numbers relevant to the code that caused the error. If you're using the Microsoft Common Dialog control within your Web page, for example, and the user clicks the Cancel button, the Err value is 32755 (assuming that you have set the common dialog's CancelError property to 1). The following code illustrates trapping this error:


Sub Button1_onClick()

On error resume next

CommonDialog1.CancelError = 1

CommonDialog1.Action = 1

If Err = 32755 Then Msgbox "Cancelled!"

end sub

Description Property

The Description property provides a human-readable description of the error that occurred. This short description can and should be displayed to the user, especially if the error was a result of user interaction. In this case, the user probably can correct the mistake that generated the error.

Source Property

This property is a string that provides the name of the object or application that caused the error condition to be raised. This string can be displayed to the user, but it's not as useful as the Description property.

If an OLE object generated the error, the Source property typically is in the form project.class.

HelpFile and HelpContext Properties

When the HelpFile property is specified by the generator of the runtime error, it should be set to the fully qualified filename of a valid Windows Help file. If the user presses the f1 key when the error dialog is open, the Help file specified is opened. The HelpContext property defines a valid context ID for a topic within the Help file. This topic should be specific to the error that was generated.

The Err Object's Methods

Like all useful objects, the Err object also has a few methods that enable you to control the behavior of the object. Methods are invoked in a manner similar to calling a procedure, but without the Call keyword. To invoke one of an object's method, you simply code object.method [parameter_list], where the optional parameter_list specifies the parameters that may be required by the method.

The Err object provides two methods: Clear and Raise. These are discussed in the following sections.

The Clear Method

The Clear method is used to clear all the properties of the Err object. The method takes no parameters and is invoked using Err.Clear.

You need to invoke the Clear method whenever you have trapped a runtime error and your script will continue execution. If you don't execute a Clear, the next time you check for an error condition, the Err object's properties still will contain the values from the previous error condition.

For example, the following code can cause problems:


On Error Resume Next

MyObject.InvokeMethod

If Err > 0 then MsgBox Err.Number & ": " &  Err.Description

MyObject.InvokeAnotherMethod

If Err > 0 then MsgBox Err.Number & ": " &  Err.Description

If MyObject.InvokeMethod caused a runtime error, the values of the Err object are set accordingly, and the first If Err > 0 Then statement is executed, displaying a message box. However, the second If Err > 0 Then also appears, regardless of whether MyObject.InvokeMethod caused a runtime error. Of course, because the Err object is global, it is possible that MyObject.InvokeMethod might execute the Err.Clear method, but it's better to be certain. The following code is more graceful:


On Error Resume Next

MyObject.InvokeMethod

If Err > 0 then

   MsgBox Err.Number & ": " &  Err.Description

   Err.Clear

End If

MyObject.InvokeAnotherMethod

If Err > 0 then

   MsgBox Err.Number & ": " &  Err.Description

   Err.Clear

End If

TIP
Notice that I used the ampersand (&) to concatenate the strings in the MsgBox calls. This behaves differently than the plus sign (+) because it causes the VBScript compiler to convert the expressions on both sides of the ampersand to strings. The plus sign does not perform this datatype conversion, so you have to use the CStr function to convert the expressions to strings.

The Raise Method

The Raise method enables you to create runtime errors within your scripts. This method really is designed to allow ActiveX component developers to create a runtime error condition within their component's code. These then are trapped by the script, as described in the section "Specifying Error Trapping," earlier in this chapter. Because the Err object is a generic object, however, the Raise method also can be used in VBScript code. One of the examples presented later in the chapter (in the section titled "Using the Raise Method") demonstrates using the Raise method in a subroutine to immediately cause an error condition.

The Raise method is invoked with this code:


Err.Raise number[,source[, description[, helpfile[, helpcontext]]]]

The values specified as parameters will be assigned to the respective properties of the Err object. The number parameter is the error number to be raised. The source parameter is a string that specifies the process that generated the error. In Internet Explorer, if this parameter is left empty, the Err.Source property value is VBScript. The description is a string describing the error condition. The helpfile and helpcontext parameters generally aren't used within VBScript code, but they specify the name of a local Help file and a context ID within that Help file. The specified Help file is displayed if the user presses f1 from within the default VBScript Error dialog.

The only required argument is number. If you don't specify the other values, however, the Err object's properties retain the values that were present in the object when you invoked the Raise method. You can use the Clear method described earlier to clear these properties before invoking the Raise method.

Looking at Examples of Error Handling

This section provides two sample VBScript pages. The first demonstrates the handling of runtime errors within a script. It uses the On Error Resume Next statement described earlier to trap runtime errors. The second example illustrates the use of the Err object's Raise method to programmatically create runtime errors. Although this might seem like a sadistic action for a programmer to take, the example presented shows how doing so in subroutines actually can be useful.

Trapping Runtime Errors

This example demonstrates how to use the On Error Resume Next statement to trap runtime errors. Listing 10.1 shows the HTML code for the sample page. This section discusses what's going on in the VBScript code as it relates to error trapping.


Listing 10.1. HTML for the runtime error-trapping example.

<HTML>

<HEAD>

<SCRIPT LANGUAGE="VBScript">

<!--

Option Explicit



Sub window_onLoad()

Dim intTemp

On error resume next



intTemp = -1

MsgBox Left("Quick Brown Fox", cint(intTemp))

if Err then

   MsgBox "Error: " & Err.description

   Err.clear

end if



intTemp = 5

MsgBox Left("Quick Brown Fox", cint(intTemp))

if Err then

   MsgBox "Error: " & Err.description

   Err.clear

else

   MsgBox "No error occurred!"

end if

end sub

-->

</SCRIPT>

<TITLE>Test Page</TITLE>

</HEAD>

<BODY>

</BODY>

</HTML>


Starting with the first <SCRIPT> tag, the first line of VBScript code (following the start of the HTML comment), is the Option Explicit directive, discussed earlier in this chapter. This prevents you from using a variable without declaring it first. You then come to the definition of the onLoad event for the main window. This is where all the code for this example is executed.

The first line of code within this event defines a variable named intTemp. This is followed by the On Error Resume Next statement. Then the value -1 is assigned to the intTemp variable, and the code attempts to use this variable as a parameter for the Left() function. Because the expression Left(string, -1) is invalid, a runtime error is produced. The next line of code following the MsgBox statement is where you check for the occurrence of a runtime error. The statement If Err then is equivalent to If Err.value > 0 then, so any value other than 0 in the Err object's value property causes this statement to evaluate to True.

A message box then is displayed, showing a description of the error. The Err object then is cleared using the Clear method. This ensures that any other references to the Err object's properties don't inadvertently use old property values.

After end if, the value of intTemp is set to 5. The same MsgBox statement is attempted again. This time, however, a valid value is passed to the Left() function, and no runtime error occurs. The Else portion of the code is executed and a box with the No error occurred! message is displayed.

Enter the HTML into the Control Pad or Notepad, save it to a file, and then open the file with the Internet Explorer. You should see a total of three message boxes: one for the runtime error, one with the message Quick, and the final one with the message No error occurred!

Using the Raise Method

The final example of this chapter illustrates how you can use the Raise method within your VBScript code. Although this method might not always be the best way to control the flow of your code, it can prove useful at times. Listing 10.2 contains the HTML code for this example.


Listing 10.2. HTML for the Raise method example.

<HTML>

<HEAD>

<SCRIPT LANGUAGE="VBScript">

<!--

Option Explicit



Sub TestRaise(blnRaiseError)

if blnRaiseError then

   Err.Raise 9000, "TestRaise", "Error from TestRaise"

end if

MsgBox "Error not called for"



end sub



Sub window_onLoad()

on error resume next



call TestRaise(1)

if Err then

   MsgBox "Error occurred: " & Err.description

   Err.clear

end if



call TestRaise(0)

if Err then

   MsgBox "Error occurred: " & Err.description

   Err.clear

end if

end sub

-->

</SCRIPT>

<TITLE>Testing Raise Method</TITLE>

</HEAD>

<BODY>

</BODY>

</HTML>


This code is very simple. The procedure TestRaise takes a single parameter, blnRaiseError. If this variable's value is greater than 0, the Raise method is invoked with some hard-coded values. This causes the procedure to immediately exit back to the calling routine. If the value is 0, a message box is displayed.

The code for the onLoad event of the main window is where you call the TestError procedure. The On Error Resume Next statement is used to trap the errors. Then TestError is called with a parameter of 1. This causes the Raise method to be invoked and the If Err then block to be entered, displaying the appropriate message box.

The code then calls TestError again, but this time with a parameter of 0. The Raise method is not invoked and the message box within the TestError procedure is displayed. No error condition exists, so when execution returns to the onLoad event, no error message box is displayed.

After this page is loaded into Internet Explorer, you see two message boxes. The first is the error message dialog stating that Error occurred: Error from TestRaise. The second is the message box within TestRaise that states Error not called for.

Review

This chapter covered the basics of error handling within VBScript code. The best way to experience how errors are handled within a particular host application (such as Internet Explorer) is to experiment with error-handling code, such as that provided in Listings 10.1 and 10.2.

From this chapter, you move on to learn how to optimize your VBScript code and then debug your code and create dynamic Web pages. By the time you finish reading this part of the book, you'll have more than enough background to proceed through the final two parts of the book.