How It Works

The TestError2 procedure operates nearly identically to the TestError procedure. TestError2 has two parameter variables.

Sub TestError2(intValue1 As Integer, intValue2 As Integer)

Microsoft Office Access

An error has occurred in the application Error Number 11

Error Description Division by zero Module Source modBusinessLogic Procedure Source: TestError2

Figure 2.44

An On Error statement specifies that the HandleError section of code should be executed when an error occurs.

On Error GoTo HandleError

A variable is declared to store the result of the division, and then the values that were passed in as parameters to the procedure are used for the division. Because the values passed in cause a divide by 0 error, the code execution skips down to the HandleError section of code.

'declare variable to store result Dim intResult As Integer

'calculate result by dividing first value by second value intResult = intValue1 / intValue2

This time, the HandleError section includes a call to the GeneralErrorHandler procedure you just added. The error number, error description, module name, and procedure name are passed as parameters to the GeneralErrorHandler procedure.

HandleError:

GeneralErrorHandler Err.Number, Err.Description, "modBusinessLogic", _ "TestError2"

Now let's turn to the GeneralErrorHandler procedure since it runs next to handle the error. The GeneralErrorHandler procedure accepts the Error Number, Error Description, Module Source, and Procedure Source as parameters.

Public Sub GeneralErrorHandler(lngErrNumber As Long, strErrDesc As String, strModuleSource As String, strProcedureSource As String)

A variable is declared to store the error message, and the error message is created based on the various values passed in to the procedure.

Dim strMessage As String

'build the error message string from the parameters passed in strMessage = "An error has occurred in the application."

strMessage = strMessage & vbCrLf &

strMessage = strMessage & vbCrLf &

strMessage = strMessage & vbCrLf &

strMessage = strMessage & vbCrLf &

"Error Number: " & lngErrNumber "Error Description: " & strErrDesc "Module Source: " & strModuleSource 11 Procedure Source: " & strProcedureSource

The error message is then displayed to the user.

'display the message to the user MsgBox strMessage, vbCritical

This generic error handler can be called from every procedure you write, changing only those variables that specify the current module and procedure. Errors can also be logged to a table, written to a file, or e-mailed, but those options are beyond the scope of this book.

0 0

Post a comment