Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get no line numbers from a stack trace created from Exceptions?

Okay; assuming this code running in debug mode -

static StackFrame GetTopFrameWithLineNumber(Exception e)
{
    StackTrace trace = new StackTrace(e);
    foreach (StackFrame frame in trace.GetFrames())
    {
        if (frame.GetFileLineNumber() != 0)
        {
            return frame;
        }
    }
    return null;
}

I'm ALWAYS returning null. Why do the stack frames have no line numbers when if I inspect the Exception.StackTrace string, it clearly does have them for any non-framework code? Is there some issue with constructing a stack trace from an exception that i'm not aware of?

EDIT FOR CLARITY: In the thrown exception I can see the line numbers in the StackTrace property. I'm assuming that means I have everything else I need.

like image 214
EightyOne Unite Avatar asked Feb 09 '10 12:02

EightyOne Unite


People also ask

How can I get the line number which threw exception?

Simple way, use the Exception. ToString() function, it will return the line after the exception description. You can also check the program debug database as it contains debug info/logs about the whole application.

Can exception stack trace null?

Yes. If you create a new Exception() and don't throw it, every property except Data and Message will be null.

What causes a stack trace error?

A stack trace shows the call stack (sets of active stack frames) and provides information on the methods that your code called. Usually, a stack trace is shown when an Exception is not handled correctly in code. (An exception is what a runtime environment uses to tell you that there's an error in your code.)


1 Answers

According to the documentation on the StackTrace constructor overload that takes an exception you can't expect line numbers when creating the StackTrace that way.

The StackTrace is created with the caller's current thread, and does not contain file name, line number, or column information.

To get the line numbers, you need to use the overload that takes a bool as well as the exception.

You also need symbol files (pdb) for line numbers. Symbol files are available for both debug and release builds.

like image 111
Brian Rasmussen Avatar answered Nov 15 '22 19:11

Brian Rasmussen