Possible Duplicate:
Show line number in exception handling
Can someone please tell me how to get the line number of the code where the error occurred and display it to the console?
Other information like the file name or method name would be very handy.
If you want the file and line numbers, you do not need to parse the StackTrace string. You can use System.Diagnostics.StackTrace to create a stack trace from an exception, with this you can enumerate the stack frames and get the filename, line number and column that the exception was raised. Here is a quick and dirty example of how to do this. No error checking included. For this to work a PDB needs to exist with the debug symbols, this is created by default with debug build.
The output from the above code looks like this
You can print the entire stack trace by using a try/catch around the code that can throw and then using Console.WriteLine to show the exception object:
Output:
The first line shows the type of the exception and the message. The second line shows the file, function and line number where the exception was thrown. You can also see the locations of other calls on the call stack in the following lines.
You can also get file and line numbers for uncaught exceptions. You can do this by adding a handler for the AppDomain.UncaughtException event on the current AppDomain:
This shows a similar output to above.
You can get the stack trace by accessing
Exception.StackTrace
which is a string so you can print it to the console by using theWrite
orWriteLine
methods.You can find it in the stack trace (
Exception.StackTrace property
), on the last line, but only when your code has been compiled with debugging information included. Otherwise the line number will be unknown.Make sure your application is in
Debug
mode or include the debug symbols (the .mdb file) in order for line numbers to appear.