Find line number of code where Exception was thrown


With the help of this article we know about how to find line number of code where Exception was thrown

This examples shows how to find the filename, method name and line number where the exception was thrown in the application.

Most of the applications log errors and exceptions in the application. It will be very useful if you can automatically log the method name and line number of the piece of code which threw the exception.

The below code sample displays the method name and the line number at which the exception was thrown.


try
{
// Some code that can cause an exception.

throw new Exception("An error has happened");
}
catch (Exception ex)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);

MessageBox.Show(trace.GetFrame(0).GetMethod().Name);
MessageBox.Show("Line: " + trace.GetFrame(0).GetFileLineNumber());
MessageBox.Show("Column: " + trace.GetFrame(0).GetFileColumnNumber());
}


Remember to use appropriate constructor for StackTrace class. Otherwise the method GetFileLineNumber() will not show line number. It may always returns 0.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: