Error Handling for Easier Development

By Mike Gunderloy

 

Of course, as an Access developer you know that you must incorporate an error handler into every procedure, or risk ugly runtime error messages in front of your users. Worse still, if you neglect an error handler in a runtime version of an Access application, any error will simply cause Access to exit, dumping the user rudely back into Windows. But did you know that you can write an error handler that makes debugging easier?

 

Here's a Function skeleton that I commonly use:

 

Function XXX () As Boolean

 

    On Error GoTo HandleErr

 

    ' Body of function goes here

 

ExitHere:

    Exit Function

 

HandleErr:

    Select Case Err.Number

        Case Else

            MsgBox "Error " & Err.Number & ": " & Err.Description, _

             vbCritical, "XXX"

    End Select

    Resume ExitHere

    Resume

 

End Function

 

Most of that will no doubt look familiar. If an error occurs anywhere in the body of the function, Access will transfer execution to the statements following the HandleErr label. The Select Case statement will always end up in the Case Else, which will put up a message with the error number and error description. Control then passes via the Resume ExitHere statement to the ExitHere label, and the function exits.

 

But why a Select Case with only one case? And why a second Resume statement that will never get executed? Ah, but it will get executed --manually, during development.

 

Here's how it works. You call the function, which of course is fiendishly complex when you've added your own application code, and an error occurs. The message box pops up on screen, but instead of clicking the OK button, you make a note of the error number and press Ctrl+Break to go into break mode. You'll find yourself in the code, with the MsgBox function in the error handler highlighted. Now use the down arrow to move the cursor past the Resume ExitHere and  on to the Resume line. Hit Ctrl+F9 to set the Resume statement as the next statement to be executed. Hit F8 to single-step, and you'll find  yourself somewhere in the body of the procedure, andwith the exact line of code that caused the error will be highlighted.

 

Of course, when you're looking at the code you can figure out how to prevent or correct the error in the future. You can then use that knowledge, together with the error number, to add a case to the Select statement to handle that particular error. As you continue development, your error traps will become more robust, catching more of the common errors. But the Case Else will always be in n there, waiting for you to go into break mode and track down another pesky problem. And the Resume statement will let you instantly home in on problem code instantly.

 


Mike Gunderloy©2001
May be distributed as long as the copyright remains.

Mike Gunderloy Bio