How to use Stacktrace to return Error Line Number in vb.net
Asked Answered
G

7

13

I am trying to create some sort of error catching method that will return the error line number. We have an abort email that is sent out when a process aborts that gives us the err.number and err.description but I would like to know where is actually errors out.

I know you can do the following:

1: code here
2: code here
3: code here

etc. and use ERL to get the number but it would be tedious to type each line out like that.

Is there either a way to automatically do this or would it be easier to use Stacktrace? If Stacktrace is better could you please show me an example?

Gerry answered 19/11, 2012 at 19:23 Comment(1)
ERL is the old way of doing things from VB6. Is there a reason not to use TRY/Catch? The exception object has a nice stack trace and includes the line number.Kile
B
11

Generating line numbers in exception stack traces is a built-in feature for the CLR. You do however have to provide the information it needs to map a code address to a line number. Switch to the Release configuration of your project. Project + Properties, Compile tab, Advanced Compile Options. Change the "Generate debug info" setting from pdb-only to Full. Deploy the .pdb files along with your program.

Beware that the line number you get is always an estimate so do not blindly trust what you see. The mapping is imperfect due to the jitter optimizer inlining methods and otherwise moving code around to make the program run faster.

Bharal answered 19/11, 2012 at 19:36 Comment(0)
E
16

I have adapted an example from other forum, in my case, I wasn't getting the line number where the error was caused, so I started playing around and found a solution, the code is as follows:

Public Class Form1
    Private Sub a2()
        Dim b As Integer = 0
        Dim a As Integer = 1 / b
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
        Try
            a2()
        Catch ex As Exception
            Dim st As New StackTrace(True)
            st = New StackTrace(ex, True)
            MessageBox.Show("Line: " & st.GetFrame(0).GetFileLineNumber().ToString, "Error")
        End Try
    End Sub
End Class

In this example, line 4 will trigger the error exception, but once I applied the principle in a real life application, line was 0, so I started playing with the index in the GetFrame property, it ranges from 0 to 4, when I put 4 in the object, EUREKA, I got the line number causing the problem.

Essentiality answered 13/10, 2013 at 17:57 Comment(4)
I tried this in the current ASP.NET application and it worked with an index on 1... My up-mark added :-)Oscillation
This SO answer shows how to do it properly: https://mcmap.net/q/904397/-getting-vb-net-line-numbers-in-stack-traceCrouch
@Oscillation don't forget to add the boolean parameter to the constructor. For me it didn't work when having parameterless constructor of StackTrace in VB.net VS13 ExpressAthletics
Can you elaborate?Oscillation
B
11

Generating line numbers in exception stack traces is a built-in feature for the CLR. You do however have to provide the information it needs to map a code address to a line number. Switch to the Release configuration of your project. Project + Properties, Compile tab, Advanced Compile Options. Change the "Generate debug info" setting from pdb-only to Full. Deploy the .pdb files along with your program.

Beware that the line number you get is always an estimate so do not blindly trust what you see. The mapping is imperfect due to the jitter optimizer inlining methods and otherwise moving code around to make the program run faster.

Bharal answered 19/11, 2012 at 19:36 Comment(0)
I
1
    Try
        Dim x As Integer
        x = " "

    Catch ex As Exception
        Dim trace = New Diagnostics.StackTrace(ex, True)
        Dim line As String = Strings.Right(trace.ToString, 5)
        Dim nombreMetodo As String = ""
        Dim Xcont As Integer = 0

        For Each sf As StackFrame In trace.GetFrames
            Xcont = Xcont + 1
            nombreMetodo = nombreMetodo & Xcont & "- " & sf.GetMethod().ReflectedType.ToString & " " & sf.GetMethod().Name & vbCrLf
        Next

        MessageBox.Show("Error en Linea number: " & line & ex.Message & vbCrLf & "Metodos : " & vbCrLf & nombreMetodo)

    End Try
Ishtar answered 1/8, 2017 at 13:8 Comment(1)
This one worked for me and I just added some minors details from https://mcmap.net/q/904397/-getting-vb-net-line-numbers-in-stack-traceJello
G
0

You should definitely use the stack trace, since you can use a global exception catching mechanism that you will need to code only once.

To get the exact line on which the error was thrown, you will need to ship the pdb files with your application. Those pdb files contain debug information, including the error's line number.

If you want to know how to catch unhandled exceptions gracefully, have a look at this codeproject article.

Godfather answered 19/11, 2012 at 19:35 Comment(0)
I
0
    Try
        Dim x As Integer
        x = " "

    Catch ex As Exception
        Dim trace = New Diagnostics.StackTrace(ex, True)
        Dim line As String = Strings.Right(trace.ToString, 5)
        Dim nombreMetodo As String = ""

        For Each sf As StackFrame In trace.GetFrames
            nombreMetodo = sf.GetMethod().Name & vbCrLf
        Next

        MessageBox.Show("Error en Linea number: " & line & vbCrLf & ex.Message & vbCrLf & "Metodos : " & nombreMetodo)
    End Try
Ishtar answered 31/7, 2017 at 21:44 Comment(1)
Please try to avoid just dumping code as an answer and try to explain what it does and why. Your code might not be obvious for people who do not have the relevant coding experience. Please edit your answer to include clarification, context and try to mention any limitations, assumptions or simplifications in your answer.Gillam
H
0

If you wish to remain using On Error Goto then simply copy and paste your code into a programmers editor like UltraEdit and insert all the line numbers in a single column editing operation. Make sure you highlight the first column then use Column/Insert Number...

Then copy and paste that back into your procedure. Voila except the first case after a select case statement. Remove the line numbers you inserted from the first case entry after every select case.

Haddock answered 15/11, 2019 at 3:47 Comment(0)
G
-1

You can use the StackTrace to retrieve the line number on an error.

Try 
    'Put your code here

Catch ex As Exception
    Dim trace = New Diagnostics.StackTrace(ex, True)
    Dim line As String = Right(trace.ToString, 5)
    MessageBox.Show("'" & ex.Message & "'" & " Error in- Line number: " & line)

End Try
Guay answered 12/4, 2016 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.