In dotNet a line throws an exception and is caught, how can I figure out which line in which file threw the exception? Seems relatively straightforward, but I can't figure it out...
You can only do it if you have debug symbols available.
catch(Exception ex) {
// check the ex.StackTrace property
}
If you want to debug such a situation in VS, you'd better just check Thrown
checkbox for Common Language Runtime Exceptions
in Exceptions
dialog located in Debug
menu. The debugger will break as soon as the exception is thrown, even if it's in a try
block.
You could use the StackFrame Class:
try
{
...
...
}
catch(...)
{
StackFrame sf = new StackFrame(true);
int lineNumber = sf.GetFileLineNumber();
int colNumber = sf.GetFileColumnNumber();
string fileName = sf.GetFileName();
string methodName = sf.GetMethod().Name;
}
Well, in .NET you have whats called a FirstChanceException. These essentially are thrown before an exception is handled. There are two ways of looking at the issue that you're presenting here. One is from a debugging angle. If debugging you can just set your debugger to catch thrown exceptions from the Debug/Exceptions window. This is easier in an interactive context. IF you need to record this information from within a non-interactive context then I would do something similar to what CMS is talking about...
try
{
...
}
catch(Exception ex)
{
System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(ex);
System.Diagnostics.StackFrame firstFrame = stackTrace.GetFrame[0];
Console.WriteLine(firstFrame.GetFileLineNumber);
...
}
The only difference here is that we get the entire Stack Trace, then go to the first frame, which is where the exception was originally thrown.
Personally, I just log the exception's ToString() return value. The whole stack trace is included. It's one line of code ... dead simple.