Determining which code line threw the exception

前端 未结 4 1303
故里飘歌
故里飘歌 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:08

    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;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-05 12:20

    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.

    0 讨论(0)
  • 2021-01-05 12:23

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

    0 讨论(0)
提交回复
热议问题