views:

322

answers:

4

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...

+5  A: 

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.

Mehrdad Afshari
This is the correct answer.
Timwi
+2  A: 

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;
}
CMS
Note however that this will return the information for the 'catch' clause... not where the exception was thrown, for that you need to check the contents of the 'StackTrace' property of the exception you caught!
jerryjvl
This answer is wrong, for the reasons jerryjvl has stated. How can this be accepted as correct?
Timwi
+1  A: 

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.

karbon
Isn't frame 0 the frame current method, not where the error originated?
Mike Rosenblum
+2  A: 

Personally, I just log the exception's ToString() return value. The whole stack trace is included. It's one line of code ... dead simple.

John MacIntyre