Visual Basic Concepts
Testing Error Handling by Generating Errors
Simulating errors is useful when you are testing your applications, or when you want to treat a particular condition as being equivalent to a Visual Basic run-time error. For example, you might be writing a module that uses an object defined in an external application, and want errors returned from the object to be handled as actual Visual Basic errors by the rest of your application.
In order to test for all possible errors, you may need to generate some of the errors in your code. You can generate an error in your code with the Raise method:
object.Raise argumentlist
The object argument is usually Err, Visual Basic's globally defined error object. The argumentlist argument is a list of named arguments that can be passed with the method. The VerifyFile procedure in the Errors.vbp sample application uses the following code to regenerate the current error in an error handler:
Err.Raise Number:=intErrNum
In this case, intErrNum
is a variable that contains the error number which triggered the error handler. When the code reaches a Resume statement, the Clear method of the Err object is invoked. It is necessary to regenerate the error in order to pass it back to the previous procedure on the call stack.
You can also simulate any Visual Basic run-time error by supplying the error code for that error:
Err.Raise Number:=71 ' Simulate "Disk Not Ready"
' error.
Defining Your Own Errors
Sometimes you may want to define errors in addition to those defined by Visual Basic. For example, an application that relies on a modem connection might generate an error when the carrier signal is dropped. If you want to generate and trap your own errors, you can add your error numbers to the vbObjectError constant.
The vbObjectError constant reserves the numbers ranging from its own offset to its offset + 512. Using a number higher than this will ensure that your error numbers will not conflict with future versions of Visual Basic or other Microsoft Basic products. ActiveX controls may also define their own error numbers. To avoid conflicts with them, consult the documentation for controls you use in your application.
To define your own error numbers, you add constants to the Declarations section of your module:
' Error constants
Const gLostCarrier = 1 + vbObjectError + 512
Const gNoDialTone = 2 + vbObjectError + 512
You can then use the Raise method as you would with any of the intrinsic errors. In this case, the description property of the Err object will return a standard description — "Application-defined or object defined error." To provide your own error description, you will need to add it as a parameter to the Raise method.
For More Information To learn more about generating your own error, see "Raise Method."