Basic Error Handling with a Centralized Message

There's one more thing you can do to make your error-handling code even easier to maintain. Instead of repeating the code to display the message box in every procedure, you can move it to a reusable function that handles it consistently every time.

The following code basically tells the user that an unexpected error occurred. It is needed in every procedure in your application.

MsgBox "An error has occurred in this application. " _ & "Please contact your technical support and " _ & "tell them this information:" _

& vbCrLf & vbCrLf & "Error Number " & Err.Number & ", " & Err.Description, _Buttons:=vbCritical, title:="My Application"

Instead, you can centralize this in a function that's called using one line:

DisplayUnexpectedError Err.Number, Err.Description

Much cleaner! This mundane bit of business is handled with just one line. Now you just need the function that it calls, DisplayUnexpectedError. Here it is:

Public Sub DisplayUnexpectedError (ErrorNumber as String, ErrorDescription as String) ' Note: since this is a universal error handling procedure, it does not have error handling

MsgBox "An error has occurred in this application. " _ & "Please contact your technical support and " _ & "tell them this information:" _

& vbCrLf & vbCrLf & "Error Number " & ErrorNumber & ", " & ErrorDescription, _Buttons:=vbCritical, title:="My Application"

End Sub

In this code, Err.Number is replaced with ErrorNumber, and Err.Description with ErrorDescription. That's necessary because you're calling a different function and sending in those two values as parameters.

This technique cleans up and shortens your code a lot, but there is an even better reason to use it. If you ever want to change the text of the message displayed to the user, you have only to change it in one place — the DisplayUnexpectedError function — instead of searching and replacing it throughout all your procedures.

Note that if you use this centralized message technique, you'll have one more step in your code when you debug using the extra Resume statement shown earlier. After you click Debug, the End Sub statement in the subroutine DisplayUnexpectedError will be highlighted. Press F8 (Step Into) once to get back to the procedure that caused the error. (This is a minor inconvenience compared to the benefit of the centralized error message.)

0 0

Post a comment