Generating Errors with the Err Object

You can generate a specific error in your code with the Raise method of the Err object. You’ve already seen this statement used to regenerate the current error in error-handling code. However, you can simulate any Visual Basic run-time error by passing the error code for that error to the Raise method. For example:

Err.Raise Number:=71			' Simulate "Disk not ready" error.

This is useful when you are testing your application, or when you want to treat a particular condition as being equivalent to a run-time error. For example, when a module calls routines in a dynamic-link library (DLL), you may want error values returned from the DLL routines to be handled as actual Visual Basic errors by the rest of your application.

You can also use the Raise method of the Err object to generate your own, user-defined errors by supplying an error code that doesn’t correspond to a Visual Basic run-time error code. Your error-handling code can handle the errors you’ve defined.

See Also   For more information on the Raise method, search the Help index for “Raise method.”

The CVErr function provides similar functionality. You can use the CVErr function to raise a user-defined error, or to defer handling of a run-time error. For example, you can create a function that evaluates its arguments to make sure they are the proper data type. If they are not, you can use the CVErr function to return an error number that you can respond to in an error-handling routine elsewhere in your code.

Function DoubleNum(intNum)
	If IsNumeric(intNum) Then
		DoubleNum = intNum * 2				' Return result.
	Else
		DoubleNum = CVErr(30000)			' Return a user-defined error.
	End If
End Function

See Also   For more information on the CVErr function, search the Help index for “CVErr function.”

Note   You need to make sure that your error numbers don’t conflict with error numbers in Visual Basic or other Microsoft Basic products. ActiveX controls, formerly called OLE controls or custom controls, may also define their own error numbers. To avoid conflicts with them, consult the documentation for any ActiveX controls you use in your application.