Alison Balteramp;#039;s Mastering Microsoft Office Access 1002003 [Electronic resources]

Alison Balter

نسخه متنی -صفحه : 544/ 273
نمايش فراداده

Examining the Cascading Error Effect

As mentioned earlier in the section "Using On Error Statements," if Access does not find any error handling in a particular subroutine or function, it looks up the call stack for a previous error handler. Listing 16.9 shows an example of this process.

Listing 16.9 Looking Up the Call Stack for a Previous Error Handler
Sub Func1() 'Invoke error handling On Error GoTo Func1_Err 'Print to the Immediate window Debug.Print "I am in Function 1" 'Execute the Func2 routine Call Func2 'Print to the Immediate window Debug.Print "I am back in Function 1" 'Exit the subroutine Exit Sub Func1_Err: 'Display a message to the user, 'indicating that an error occurred MsgBox "Error in Func1" 'Resume execution Resume Next End Sub Sub Func2() 'No error handling in this routine! 'Print to the Immediate window Debug.Print "I am in Func2" 'Execute Func3 Call Func3 'Print to the Immediate window Debug.Print "I am still in Func2" End Sub Sub Func3() 'No error in this routine either! Dim sngAnswer As Single 'Print to the Immediate window Debug.Print "I am in Func3" 'Oops, an error occurred sngAnswer = 5 / 0 'This line of code will never execute Debug.Print "I am still in Func3" End Sub

In this situation, the error occurs in Func3. Because Func3 does not have its own error handling, it refers back to Func2. Func2 does not have any error handling either, so Func2 relinquishes control to Func1. VBA executes the error code in Func1. The real problem occurs because of the Resume Next statement. The application continues executing within Func1 on the Debug.Print "I am back in Function 1" statement. This type of error handling is dangerous and confusing. Therefore, it is best to develop a generic error-handling routine that is accessed throughout your application. The creation of a generic error handler is discussed in the section "Creating a Generic Error Handler."