Determining which code line threw the exception

前端 未结 4 1404
故里飘歌
故里飘歌 2021-01-05 11:56

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

4条回答
  •  滥情空心
    2021-01-05 12:14

    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.

提交回复
热议问题