![]() |
![]() |
![]() |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
![]() |
![]() |
To access the contents, click the chapter and section titles.
Visual Basic 6 Programming Blue Book: The Most Complete, Hands-On Resource for Writing Programs with Microsoft Visual Basic 6!
The ERR ObjectMuch of Visual Basics ability to deal with errors comes from the ERR object. Each Visual Basic program automatically has a single ERR object associated with it. ERR has global scope, meaning it can be accessed from anywhere in a program. At any moment, ERR contains (in its properties) information about the most recent error that has occurred. The properties youll need most often are these:
The first two properties of the ERR object provide the same numerical code and text description displayed in the error dialog box when an untrapped error occurs. As such, they do not provide a great deal of information. The value of these properties lies in giving your program access to this information in code, enabling it to determine which error occurred and then to take appropriate action. The Source property is not much use in a self-contained application, because it will return only the name of the Visual Basic project. It is more useful when using external objects, as covered later in the chapter. Lets look at an example. If a program uses a diskette drive, a common potential error that should be trapped is the absence of a diskette in the drive. Attempting to open a file under these conditions results in error number 71. The error-handling code would look something like Listing 25.2. Listing 25.2 Using the ERR objects Number property to identify the error. Private Sub SaveData() Dim f As Long On Error GoTo FileError f = FreeFile Open a:\junk.dat For Binary As #f ' Code to write data goes here. Close #f Exit Sub FileError: If Err.Number = 71 Then MsgBox (Please insert a diskette in drive A:, then click OK) Resume End If End Sub If there is no diskette in drive A: when this procedure executes, attempting to execute the Open statement will cause error number 71 to occur. Execution will pass to the FileError label, and the ERR objects Number property will be tested against the value 71. Because it matches, the program will display a message box prompting the user to insert a diskette. When the user closes the message box, the Resume statement will cause execution to continue with the statement that caused the errorin this case, the Open statement. Because a diskette is now in the drive, the statement will execute with no error. Although the code in Listing 25.2 works, you would not want to place it in a real program. Suppose the user does not have a diskette handy. The program should offer the option of canceling the disk write operation. Listing 25.3 shows an improvement on the previous example, providing the user with the option of inserting a diskette and continuing, or canceling. Listing 25.3 Improved error-handling code offers the user a choice. Private Sub SaveData() Dim f As Long, Reply As Integer Dim msg As String On Error GoTo FileError f = FreeFile Open a:\junk.dat For Binary As #f ' Data writing code goes here. Close #f Exit Sub FileError: If Err.Number = 71 Then msg = Please insert a diskette in drive A:, then click Retry. msg = msg & VbCRLF msg = msg & Or click Cancel to try again later. Reply = MsgBox(msg, vbRetryCancel, Disk error) If Reply = vbRetry Then Resume ElseIf Reply = vbCancel Then Resume Finish End If ' Other error handling code goes here. Finish: End If End Sub Now when error number 71 is trapped, a message box is displayed offering users the choice of inserting a disk immediately or canceling the save operation and trying again later (a desirable option for some situationsif the user happens to be out of diskettes and must go fetch one, for example). If the user selects Retry, the Resume statement is used to re-execute the Open statement. If the user selects Cancel, the Resume label is used to direct execution out of the procedure. While improved over the original, this error-handling code is still incomplete. If a different error occurred, execution would still pass to FileError. The If condition would not be True, however, so the associated statements would not be executed. Instead, execution would leave the procedure, and the error would be left hanging. Does this mean the error-handling code in each procedure must explicitly deal with every single possible error? No, that would be impractical. Ill show you how to create a more generic error handler later in the chapter. Sometimes, error-handling code will test the value of ERR.Number as soon as the error is trapped (as in the previous example). At other times, the numerical error value will not be tested immediately. When this happens, you retrieve the value of ERR.Number and save it in a regular variable. Why? Remember that the ERR object contains information about the single most recent error. If a second error occurs between the time of the first error and retrieving the value of ERR.Number, you receive the numerical code for the second error; information about the first error is lost. As you might well imagine, Visual Basic has a whole slew of trappable errors. How do you find out about them? Activate the Visual Basic Help system and search for trappable errors to receive a list of error message categories, such as OLE Automation Messages and Miscellaneous Messages. Select the desired category for a list of related errors and their numerical codes. Select an individual error message to view more details on the causes and possible remedies (if any) for the error condition.
Using On Error Resume NextAs I have already mentioned, executing the On Error Resume Next statement is necessary when you want to defer error trapping. If this statement is in effect when an error occurs, execution continues with the statement immediately following the one that caused the error. This type of deferred error trapping is most useful when our program is accessing objectssuch as OLE automation objectsbecause it permits you unambiguously to identify the object that caused the error. The basic sequence of code is as follows:
Listing 25.4 illustrates this technique. The code attempts to use the GetObject function to access a nonexistent object. This causes error 432, defined as File name or class name not found during OLE Automation operation. The If statement tests for this value in Err.Number, and if it is found, displays a dialog box with a message including the name and source of the error. The error source is obtained from the ERR objects Source property, which contains the name of the object or application that caused the most recent error. In this example, it will return the name of the Visual Basic project. In other cases, such as passing a nonsupported command to an existing OLE Automation object, the object name will be returned. Finally, the Clear method is executed to clear all of the ERR objects properties. This ensures that the old information from this error will not hang around and be misinterpreted later. The Clear method is invoked automatically whenever an On Error, Resume, Exit Sub, or Exit Function statement is executed. Listing 25.4 Demonstrating deferred error handling when accessing objects. Private Sub AccessObject() Dim MyObj As Object Dim msg As String On Error Resume Next ' Defer error trapping. ' Try to start a non-existent object. MyObj = GetObject(MyWord.Basic) ' Test for error 432 If Err.Number = 432 Then ' OLE Automation error. ' Tell user what happened. msg = An error occurred attempting to open the OLE object! msg = msg & VbCRLF msg = msg & Error source: & Err.Source msg = msg & VbCRLF & Error number: & Err.Number MsgBox (msg) ' Clear the Err object properties. Err.Clear End If End Sub Raising ErrorsWhen working on your projects error-handling code, mimicking the occurrence of certain runtime errors is often useful, so you can see exactly how your error-handling routines work. You can mimic errors in code using the ERR objects Raise method. The syntax is as follows: Err.Raise number, source, description, helpfile, helpcontext The only required argument is number, which is a Long integer that identifies the error. To mimic a specific Visual Basic error, use the number associated with the error, as indicated in the Help information. The other arguments are optional:
The following line of code, for example, will simulate a Disk not ready error: Err.Raise 71
|
![]() |
Products | Contact Us | About Us | Privacy | Ad Info | Home
Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement. |