Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 402
user1836775 Avatar asked Nov 19 '12 19:11

user1836775


People also ask

How to get error line number in vb net?

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. Save this answer.

What is exception StackTrace?

A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs. The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown.


1 Answers

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.

like image 173
Mauricio Avatar answered Sep 19 '22 05:09

Mauricio