Tutorial :Outputting line numbers


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?


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.)


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


Just wanted to correct Noldorin's response because s/he used the wrong Stacktrace constructor:

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

Specifying True as the second argument for the constructor tells it to capture the stack source information at the time of creation. Without it stackFrame.GetFileLineNumber() 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 that Noldorin suggested. Note the remarks section which states:

The StackTrace is created with the caller's current thread, and does not contain file name, line number, or column information.

The resulting stack trace describes the stack at the time of the exception.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »