Output line numbers
Is there a way in VB.NET to output the current line number in source code? For instance:
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 a way to fill the LineNumber variable in the above example with the actual line number in the source code that caused the error?
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, it is a frame containing the current try-catch block you want. For more information see the MSDN docs .
a source to share
Just wanted to correct Noldorin's answer because he was using the wrong Stacktrace constructor:
Dim stackTrace = New System.Diagnostics.StackTrace(ex, True)
Dim stackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1)
Dim lineNumber = stackFrame.GetFileLineNumber()
An assignment True
as the second argument to the constructor tells it to write the stack source information at creation time. Without it, stackFrame.GetFileLineNumber()
it will always return 0.
See http://msdn.microsoft.com/en-us/library/dsay49kt.aspx for an explanation of the correct constructor and http://msdn.microsoft.com/en-us/library/25h0kw08.aspx to show the constructor. proposed by Noldorin. Take a look at the remarks section which says:
StackTrace is created with the current call flow, and does not contain file name, line number, or column information.
The resulting stack trace describes the stack at the time of the exception.
a source to share