• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Creating a Call Stack

While in the debugger, it is very easy to view the call stack. Unfortunately, the call stack information cannot be accessed programmatically when an error occurs. If you want to keep track of the sequence of procedures that brought you to the error condition, you must do it yourself. The code in Listing 16.26 shows three routines. Func1 calls Func2, and then Func2 calls Func3. Func3 renders an error.

Listing 16.26. Routines That Call One Another

Sub Func1()

    'Invoke error handling
    On Error GoTo Func1_Err

    'Put routine in call stack
    ERH_PushStack_TSB ("Func1")

    '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"

Func1_Exit:

    'Pop error stack
    ERH_PopStack_TSB

    '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 Func1_Exit
End Sub

Sub Func2()
    'Put routine in call stack
    ERH_PushStack_TSB ("Func2")

    On Error GoTo Func2_Err

    Debug.Print "I am in Func2"

    'Execute Func3
    Call Func3

    'Print to the Immediate window
    Debug.Print "I am still in Func2"

Func2_Exit:

    'Pop error stack
    ERH_PopStack_TSB

    'Exit the subroutine
    Exit Sub

Func2_Err:
    'Display a message to the user,
    'indicating that an error occurred
    MsgBox "Error in Func1"

    'Resume execution
    Resume Func2_Exit

End Sub

Sub Func3()
    Dim sngAnswer As Single

    'Put routine in call stack
    ERH_PushStack_TSB ("Func3")

    On Error GoTo Func3_Err

    '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"

Func3_Exit:

    'Pop error stack
    ERH_PopStack_TSB

    'Exit the subroutine
    Exit Sub

Func3_Err:
    Dim intCounter As Integer
    Dim strCallStack As String

    For intCounter = LBound(gaERH_Stack_TSB) To UBound(gaERH_Stack_TSB)
        If Len(gaERH_Stack_TSB(intCounter)) Then
            strCallStack = strCallStack & _
                gaERH_Stack_TSB(intCounter) & vbCrLf
        End If
    Next intCounter

    MsgBox Err.Number & ": " & Err.Description & _
        vbCrLf & strCallStack

    Resume Func3_Exit
End Sub


					  


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint