views:

158

answers:

1

How to identify the line nr. where the exception has occured and show a piece of code around the exception?

I would like to implement a custom exception handler page which would display the stack trace, and I'm looking for the easiest way to accomplish the above. While most of the information is available through the Exception object, the source code information is not available there.

+1  A: 

You need to use the StackTrace class.

For example:

var st = new StackTrace(exception, true);

var sourceFrame = Enumerable.Range(0, st.FrameCount).FirstOrDefault(i => st.GetFrame(i).GetFileLineNumber() > 0);

This code will find the first frame which has line number information available, or null, if none of the frames have line numbers.

You can then call the methods of the StackFrame object to get more information. Note that source information is usually only available in debug builds.

SLaks
Great! thanks a bunch!
Andy