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.
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.
Yes. If you create a new Exception() and don't throw it, every property except Data and Message will be null.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With