Previous Page

Guidelines for Complex Error Handling

When you create large applications that use multiple modules, the error-handling code can get quite complex. Keep these guidelines in mind:

 Reduce code size by writing a few procedures that your error-handling code can call to handle common error situations. For example, you may want to write a procedure to handle file-related and disk-related errors that you call whenever you read or write to a disk file.

 Use the Raise method of the Err object in all error-handling code to handle cases in which no code in the error-handling routine deals with the specific current error. This enables your application to try to correct the error in other error-handling routines along the calls list. It also ensures that Visual Basic displays an error message if an error occurs that your code doesn't handle. This helps you uncover the errors you aren't handling adequately when you test your code.

 Use the Clear method if you need to explicitly clear the Err object after handling an error. This is necessary when using inline error handling with the On Error Resume Next statement. Visual Basic calls the Clear method automatically whenever it runs any type of Resume statement, Exit Sub, Exit Function, Exit Property, or any On Error statement.

See Also   For more information on inline error handling, see "Inline Error Handling" later in this chapter.

 If you don't use the Raise method, you can write fail-safe error-handling code that all your error handlers can call as a last resort. For example, such code may try to close forms and save a user's data.

 If you don't want a previous procedure to trap the error, use the Stop statement in the error-handling code to force your application to close. By using the Stop statement, you can examine the context of the error while refining your code. Be sure to remove these Stop statements before you distribute your application to users.

© 1996 Microsoft Corporation. All rights reserved.

Next Page


Casa de Bender