Is it possible to retrieve the call stack programmatically in VB6?

后端 未结 5 1991
天涯浪人
天涯浪人 2020-12-03 21:25

When an error occurs in a function, I\'d like to know the sequence of events that lead up to it, especially when that function is called from a dozen different places. Is t

5条回答
  •  抹茶落季
    2020-12-03 21:59

    You do have to do it the hard way, but it's not really all that hard... Seriously, once you've written the template once, it's a quick copy/paste/modify to match the function name in the Err.Raise statement to the actual function name.

    Private Function DoSomething(ByVal Arg as String)
    
        On Error GoTo Handler
    
        Dim ThisVar as String
        Dim ThatVar as Long
    
        ' Code here to implement DoSomething...
    
        Exit Function
    
    Handler:
        Err.Raise Err.Number, , "MiscFunctions.DoSomething: " & Err.Description
    
    End Function
    

    When you have nested calls, this unwinds as each routine hits its Handler and adds its name to the error description. At the top level function, you get a "call stack" showing the list of routines that were called, and the error number and description of the error that actually occurred. It's not perfect, in that you don't get line numbers, but I've found that you don't usually need them to find your way to the problem. (And if you really want line numbers, you can put them in the function and reference them in the Err.Raise statement using the Erl variable. Without line numbers, that just returns 0.)

    Also, note that within the function itself, you can raise your own errors with the values of interesting variables in the message like so:

    Err.Raise PCLOADLETTER_ERRNUM, , "PC Load Letter error on Printer """ & PrinterName & """"
    

    (The syntax highlighting looks wonky in the preview... I wonder how will it look when posted?)

提交回复
热议问题