tags:

views:

242

answers:

2

I have a few VB.NET programs to maintain, that have been ported from VB6 and use the old style Unstructured Exception Handling:

On Error GoTo yyy

My question is, can I still get a stack trace while using Unstructured Exception Handling, or do I have to convert them all to Structured Exception Handling (Try/Catch) in order to catch an exception with its full stack trace.

+2  A: 

As you know yourself, all things being equal, one should always use structured exception handling. However, if you can't, you can get your own stack trace by using the StackTrace class.

NB: Calls to stack trace are expensive, and should only be used in - ahem - 'exceptional' circumstances.

e.g

MethodName = (New StackFrame(0)).GetMethod.Name ' Get the current method
MethodName = (New StackFrame(1)).GetMethod.Name ' Get the Previous method
MethodName = (New StackFrame(2)).GetMethod.Name ' Get the method before that
Binary Worrier
This just gives a stack trace to the routine where the error handler is. If you want to know the line that caused the exception, and which routine that was in, see my answer ;)
MarkJ
+3  A: 

Here's a way to get the stack trace to the line that caused the exception, unlike the other answer which just traces to the routine where your error handler is. The error might have occurred in a different routine.

In the unstructured error handlers, just use the GetException property of the Err object to access the underlying exception - then use the StackTrace property. Like this:

Public Class Form1

Public Sub New()

    ' This call is required by the Windows Form Designer.' 
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.' 
    On Error GoTo ErrHandle

    Call test()        
    Exit Sub 

ErrHandle:
    MsgBox("Stack trace " & Err.GetException.StackTrace)
    Exit Sub

End Sub 


Private Sub test()
    Call test2()
End Sub

Private Sub test2()
    Dim d(2) As Double

    MsgBox(d(-1))
End Sub
End Class
MarkJ
Nice one, I didn't know about this, thanks :)
Binary Worrier