Tutorial :Can I get the line of code that caused an exception?



Question:

Other than reading the GetFileName() file and reading to line GetFileLineNumber() of a stackframe from

new StackTrace(exception).GetFrame(x)  

is there a way to get the actual line of code (as a string) which caused an exception?

Thanks


Solution:1

Post moretem debugging is difficult, but not impossible. There are tools you can use (here and here for example) as well as techniques.


Solution:2

I don't think so. The code is compiled, therefore it is no longer available. However, if you also have the source code available, there may be a few workarounds.


Solution:3

No, that's your only option as far as I know. In order to get the original line of code that caused the exception, then it's necessary to have the source available. That the StackFrame already enables you to get the line number (via the debug symbols - the PDB file in most cases), makes it straightforward enough, I'd say.

Is there any particular problem with the method you suggested?


Solution:4

There is no reliable way to do this because line information is not stored in DLL files. The information which maps blocks of IL into source code lines is stored within the PDB file. You'd need to access the PDB in order to get the line information for an exception.

There is sufficient information on the StackFrame class to get the appropriate ISymUnmanagedMethod class if the PDB is available. Mainly you just need the method token and the current offset into the method. This does require you to understand the internal structure of the PDB and I'm not sure if it's documented anywhere.

PDB API: http://msdn.microsoft.com/en-us/library/ms233503.aspx


Solution:5

It would be compiled, so at run time you would only have the IL. At best, you could get the IL and decompile it back to C#, much like reflector does.


Solution:6

You can get line using a try catch block:

catch(Exception exception) {      //exception.StackTrace at the first line has the line you are looking for  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »