![]() |
![]() |
![]() |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
![]() |
![]() |
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!
User-Defined ErrorsIn addition to dealing with runtime errors, you can use Visual Basics error-handling capabilities to define your own errors. Two approaches are possible: raising errors that you define and returning errors from functions. Raising Your Own Errors The first approach is to assign an unused error number to an occurrence that you want to treat as an error. When the error condition occurs (as determined by your code), you use the Raise method to trigger the error and Visual Basics usual error-handling methods (OnError Goto, and Resume) to deal with it. Thus, a procedure could contain one error handler that deals with both regular system errorssuch as disk drives not being readyas well as your user-defined errors. Lets try an example. Create a new project with a single form, placing the code in Listing 25.5 in the forms Click event procedure. When you run the project and click on the form, you will be prompted to enter a nameany name, except Bill. If you follow instructions and enter, say, Gladys, you will be rewarded with a Thank You message. If you enter Bill, however, the If statement uses the Raise method to trigger an error with the Number 1234 and the Description Not Bill, dummy! The On Error Goto statement specifies that execution was to pass to the location identified by the label ErrorHandler. Code in the error handler checks to see if the error was the user-defined error identified by the Number property 1234. If so, the code displays a message consisting of the errors Description property. Listing 25.5 Using the Raise method to generate user-defined errors. Private Sub Form_Click() Dim buf As String On Error GoTo ErrorHandler GetData: buf = InputBox(Enter any name except 'Bill'.) If buf = Bill Then Err.Raise 1234, , Not Bill, dummy! MsgBox (Thank you) Exit Sub ErrorHandler: If Err = 1234 Then MsgBox (Err.Description) Resume GetData End If End Sub Error numbers from 0 to 1000 are reserved for use by Visual Basic (although not all of them are actually used). In regular codecode that is not in a class moduleyou can use any number between 1001 and 65535. When raising an error in a class module, you must add your error code number to the vbObjectError constant. For example, if the previous code were in a class module, you would write the following: If buf = Bill Then Err.Raise vbObjectError + 1234, , Not Bill, dummy! Returning Errors From Functions The second approach to user-defined errors allows you to return an error value from a function. By returning an error value rather than the normal return value, you can signal the calling code that an error has occurred within the function. But how do you distinguish an error value from a nonerror value? The technique makes use of the flexibility of the Variant data type. Recall from Chapter 4 that a Variant can hold a variety of subtypes of dataone of which is Error. To convert a regular number into a type Error, you use the CVErr function. Thus, if X and Y are both type Variant variables, the code X = 1234 Y = CVErr(1234) results in X containing a subtype Integer and Y containing a subtype Error. Both have the same numerical value, but the subtype is different. You can tell if a Variant contains an Error subtype with the IsError function. When passed a type Variant, this function returns True if the subtype is Error; otherwise, it returns False. Listing 25.6 shows an example of using this type of user-defined error. Two procedures are included here: one is a general function; the other is the Click event procedure for the projects form. When you run the project (assuming you know enough by now to create a new project and add these procedures on your own), click on the form, and the program will prompt you for a number. Your entry is passed to the SquareRoot function, and the following steps occur:
It is now up to the calling program to test the value returned by the SquareRoot function to determine if an error has occurred. This is done in two stages. First, the IsError function is used to determine if the return value is type Error. If it is not, the function returns a valid answer, and you can display it. If an Error is returned, the next step is testing the value that was returned to determine which type of error occurred. Note that you use the CInt function to convert the type Error value into a plain type Integer before comparing it with the constants 1001 and 1002. You could also have written the following, and it would work just as well: If answer = CVErr(1002) Then Listing 25.6 Returning a type Error from a function. Public Function SquareRoot(X As Variant) If Not IsNumeric(X) Then SquareRoot = CVErr(1001) ElseIf X < 0 Then SquareRoot = CVErr(1002) Else SquareRoot = X ^ 0.5 End If End Function Private Sub Form_Click() Dim num As Variant, answer As Variant num = CVar(InputBox(Enter number for square root:)) answer = SquareRoot(num) If IsError(answer) Then If CInt(answer) = 1002 Then MsgBox (Positive numbers only, please!) Exit Sub End If If CInt(answer) = 1001 Then MsgBox (That's not a number!) Exit Sub End If End If MsgBox (The square root of & num & is & answer) End Sub General Error-Handling CodeAs I mentioned earlier, explicitly testing for every individual error that might conceivably occur in each procedure is not practical. Does this mean you can just ignore other errors? Not necessarily. You may not be able to explicitly handle an unexpected error, but at least you can inform the users of the nature of the error, so they can report it to you, permitting you to fix the problem in the code. The goal is to provide information about the nature of the error and where it occurredboth in terms of which form and which procedure it is in. You can obtain the name of the form from the property Screen.ActiveForm.Name. As for determining the procedure, declare a string variable and load it with the procedure name. An example is shown in Listing 25.7. Listing 25.7 Code for reporting information on untrapped errors. Dim ProcName As String ProcName = Form_DblClick On Error GoTo ErrorHandler ' Other code here ErrorHandler: msg = An untrapped error has occurred. Please make a & VbCRLF msg = msg & note of the following information. & VbCRLF & VbCRLF msg = msg & Error number: & Err.Number & VbCRLF msg = msg & Description: & Err.Description & VbCRLF msg = msg & Location: & Screen.ActiveForm.Name & VbCRLF msg = msg & Procedure: & ProcName MsgBox (msg) Perhaps more than any other aspect of a Visual Basic Program, the burden for well-designed error handling rests on the programmer. There are no clever controls that you can drop in to do the job for you. The errors that need to be addressed and the way they are handled will depend to a large degree on the specifics of your program. Its tempting to skimp on error handling or to leave it for the end of the project. Wrong! Keep error handling in mind from the start, building it right into your programnot tacking it on at the end. Youll save time and grief in the long run. Trust me on thisI know from experience.
|
![]() |
Products | |