Results 1 to 7 of 7

Thread: Method to find the exact line of code that caused an error in VB.NET using Try Catch

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Feb 2020
    Posts
    70

    Method to find the exact line of code that caused an error in VB.NET using Try Catch

    When an error occurs while executing the project (in this case, dividing by zero), the message box displays the exception details, including the file path, procedure and line number where the error occurred, such as "Form1.vb:line 5".
    Code:
    Public Class Form1
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            Try
                Dim d As Integer
                Dim c As Integer = d / 0
                MsgBox(c.ToString)
            Catch ex As Exception
                MsgBox(ex.toString)
            End Try
        End Sub
    End Class
    For the above code, Is there any code that can be placed in catch part so that message box should display the exact line of code that caused the error, i.e., "Dim c As Integer = d / 0" which would be helpful for logging spcific line of code where error occured for larger coding projects.

    I want to get the line of code along with line number details for easier Debugging.
    Last edited by IT_Researcher; Dec 5th, 2024 at 03:40 AM.

  2. #2
    Fanatic Member
    Join Date
    Jul 2022
    Location
    Buford, Ga USA
    Posts
    630

    Re: Method to find the exact line of code that caused an error in VB.NET using Try Ca

    You can use the stack trace (a map to the line causing an error) in your message box message. Like:
    Code:
    Public Class Form1
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            Try
    	    Dim d As Integer
    	    Dim c As Integer = d / 0
    	    MsgBox(c.ToString)
    	Catch ex As Exception
    	    MsgBox($"{ex.toString} {ex.message} {ex.stacktrace}")
    	End Try
        End Sub
    End Class

    More on what Exception has available. https://learn.microsoft.com/en-us/do...and-properties

    edit: format the code block
    edit2: more on the use of $ to create the string for the message https://learn.microsoft.com/en-us/do...olated-strings
    Last edited by jdelano; Dec 4th, 2024 at 05:29 AM.

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Method to find the exact line of code that caused an error in VB.NET using Try Ca

    Quote Originally Posted by jdelano View Post
    format the code block
    Indeed. Not surprisingly, the QUOTE tag is for posting a quote and the CODE tag is for posting code.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Method to find the exact line of code that caused an error in VB.NET using Try Ca

    Quote Originally Posted by IT_Researcher View Post
    Is there any code that can be placed in catch part so that message box should display the exact line of code that caused the error, i.e., "Dim c As Integer = d / 0" which would be helpful for logging specific line of code where error occurred for larger coding projects.
    No there isn't, but why would you need it? More often than not, the actual line of code is not much use witho9ut the context. If you have the file and the line number then you can get the line of code that refers to anyway, along with the context.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: Method to find the exact line of code that caused an error in VB.NET using Try Ca

    The actual line of code might even be misleading. Consider the Null Reference Exception. That just means that an object that you are trying to do something with is Nothing. The exception will take you to the line where you tried to do something with the object, and that may be all you need to see, but usually, the question is, "why is that object Nothing?" The answer to that question is rarely found on the line that throws the exception, but is usually found earlier.

    Then consider what happens with optimization, where lines of source code may not correspond to much of anything in the executing code, as things might have been optimized away. Whatever line throws the exception will correspond to some line of source code, but it need not be the right one, just in the vicinity of the right one.

    The stack trace is the most valuable item, as it puts you in the right vicinity, but it isn't all you ever need, it's just all you can have to start out with.
    My usual boring signature: Nothing

  6. #6
    Fanatic Member
    Join Date
    Jul 2022
    Location
    Buford, Ga USA
    Posts
    630

    Re: Method to find the exact line of code that caused an error in VB.NET using Try Ca

    Quote Originally Posted by jmcilhinney View Post
    Indeed. Not surprisingly, the QUOTE tag is for posting a quote and the CODE tag is for posting code.
    When I use Notepad3 and paste it here, it over indents, like it seems to double the tabs. Fixing it just eased my senses.

  7. #7
    Wall Poster TysonLPrice's Avatar
    Join Date
    Sep 2002
    Location
    Columbus, Ohio
    Posts
    3,969

    Re: Method to find the exact line of code that caused an error in VB.NET using Try Ca

    Here is what I use. I got it off the internet many years ago:

    Code:
        Public Function GetExceptionInfo(ex As Exception) As String
            Dim Result As String
            Dim hr As Integer = Runtime.InteropServices.Marshal.GetHRForException(ex)
            Result = ex.GetType.ToString & "(0x" & hr.ToString("X8") & "): " & ex.Message & Environment.NewLine & ex.StackTrace & Environment.NewLine
            Dim st As StackTrace = New StackTrace(ex, True)
            For Each sf As StackFrame In st.GetFrames
                If sf.GetFileLineNumber() > 0 Then
                    Result &= "Line:" & sf.GetFileLineNumber() & " Filename: " & IO.Path.GetFileName(sf.GetFileName) & Environment.NewLine
                End If
            Next
            Return Result
        End Function
    I use it like this:

    Code:
    Catch ex As Exception
                mErrorMessage = "Error in btnStartInput - Line number: " & GetExceptionInfo(ex)
                MsgBox(mErrorMessage)
                Me.Cursor = Windows.Forms.Cursors.Default
                Exit Sub
            End Try
    The gurus here might pick it apart but I have found it to be very reliable and use it all over the place. It rarely fails me but our applications are mainly straight business without a lot of bells and whistles. Sometimes it brings back multiple lines numbers but one will be it.
    Last edited by TysonLPrice; Dec 4th, 2024 at 11:33 AM.
    Please remember next time...elections matter!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width