How can I get the line number which threw exception?

MBZ picture MBZ · Jul 25, 2010 · Viewed 211.3k times · Source

In a catch block, how can I get the line number which threw an exception?

Answer

Quartermeister picture Quartermeister · Jul 25, 2010

If you need the line number for more than just the formatted stack trace you get from Exception.StackTrace, you can use the StackTrace class:

try
{
    throw new Exception();
}
catch (Exception ex)
{
    // Get stack trace for the exception with source file information
    var st = new StackTrace(ex, true);
    // Get the top stack frame
    var frame = st.GetFrame(0);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();
}

Note that this will only work if there is a pdb file available for the assembly.