Condividi tramite


Visual Basic Concepts

Deciding How to Generate Error Messages

When an application calls a method of an object your component provides, there are two general ways in which the method can provide error information.

  • Basic-style: The method can raise an error. The client application can implement an error handler to trap errors that may be raised by the method.

  • Windows API-style: The value returned by the method can be an error code. The client application can examine the return value to determine whether an error has occurred.

There are a number of programming tradeoffs to consider when you select an error generation strategy for your component, but the most important consideration should be the convenience of the developer who will use your component.

For example, if your methods always return an error value, the developer using your component must use in-line error handling, that is, the developer must always test the return value after calling a method. This is the way Windows API calls work.

If you raise errors, on the other hand, the developer has the choice of implementing in-line error handling (On Error Resume Next) or writing error-handling routines (On Error GoTo). This flexibility is a hallmark of the coding style familiar to Basic developers.

Be Consistent

Whichever error generation strategy you adopt, be consistent. Developers will not appreciate having to test return values from some methods, and trap errors from others. The more difficult it is to use a component, the less benefit there is from re-using the code.

If you decide to return error values instead of raising them, it’s better for all return values to be error codes. This means that if a method also returns a data value, you must use a ByRef parameter for the data. While this is an inconvenience for the user of the method, it’s less of an inconvenience than having to test the data type of a return value, to see whether it’s an error, before using it as a data value.

Note   Client applications that use out-of-process components should always employ some form of error handling, because failures in the underlying cross-process communication layer will be raised as errors in the client application.

For More Information   "Raising Errors from Your Component" discusses standards and techniques for raising errors from ActiveX components.