Exception handling -- Display line number where error occurred?

CSharp Noob picture CSharp Noob · Apr 27, 2010 · Viewed 35.3k times · Source

Possible Duplicate:
Show line number in exception handling

Can someone please tell me how to get the line number of the code where the error occurred and display it to the console?

Other information like the file name or method name would be very handy.

Answer

Chris Taylor picture Chris Taylor · Apr 27, 2010

If you want the file and line numbers, you do not need to parse the StackTrace string. You can use System.Diagnostics.StackTrace to create a stack trace from an exception, with this you can enumerate the stack frames and get the filename, line number and column that the exception was raised. Here is a quick and dirty example of how to do this. No error checking included. For this to work a PDB needs to exist with the debug symbols, this is created by default with debug build.

using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
  class Program
  {    
    static void Main(string[] args)
    {      
      try
      {
        TestFunction();
      }
      catch (Exception ex)
      {
        StackTrace st = new StackTrace(ex, true);
        StackFrame[] frames = st.GetFrames();

        // Iterate over the frames extracting the information you need
        foreach (StackFrame frame in frames)
        {
          Console.WriteLine("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber());
        }
      }

      Console.ReadKey();
    }

    static void TestFunction()
    {      
      throw new InvalidOperationException();
    }
  }
}

The output from the above code looks like this

D:\Source\NGTests\ConsoleApplication1\Program.cs:TestFunction(30,7)
D:\Source\NGTests\ConsoleApplication1\Program.cs:Main(11,9)