views:

108

answers:

2

Is there a way, in VB.NET, to output the current line number in the source code? For example:

Try
    ' The following line will purposly cause an error
    Dim BigNum As Int64
    Dim LittleNum As Int16 = CShort(BigNum)
Catch ex As Exception
    Dim LineNumber As Integer = <linenumber> ' How do I do this?
    MessageBox.Show("Error in source code. Line: " + LineNumber)
End Try

Is there any way to fill the LineNumber variable in the example above with the actual line number in the source code that caused the error?

A: 

The line number will be in the Exception's stack trace already. I think it even shows in a simple ex.ToString.

Daniel Straight
+2  A: 

This should do the job:

Dim stackTrace = New System.Diagnostics.StackTrace(ex)
Dim stackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1)
Dim lineNumber = stackFrame.GetFileLineNumber()

Note that GetFrame(stackTrace.FrameCount - 1)) gets the first frame pushed onto the stack. In this case, this is the frame containing the current try-catch block, which is what you want. See the MSDN docs for more info.)

Noldorin
Thank you. This looks like its exactly what I was looking for!
Glad to help. Unless you have any further queries, would you mind accepting it as answer?
Noldorin
I tried it out, but the StackFrame contains no information (GetFileName returns Nothing and GetFileLineNumber returns 0). Did I miss something?
Fredrik Mörk
@Fredrik: It definitely works. You must however be running in debug mode with symbols loaded - insure that that is the case.
Noldorin
Running debug with symbols loaded; it surprised me that I didn't get it to work since this was the solution that immediately came to my mind as well. Probably some issue with my environment though, I would suspect, I trust your solution to work.
Fredrik Mörk
@Fredrik: Yeah, that sounds quite unusual. Indeed it is probably some issue specific to your environment.
Noldorin