How can I get the line number which threw exception?

后端 未结 12 2205
既然无缘
既然无缘 2020-11-27 09:14

In a catch block, how can I get the line number which threw an exception?

12条回答
  •  盖世英雄少女心
    2020-11-27 10:14

    If you need the line number for more than just the formatted stack trace you get from Exception.StackTrace, you can use the StackTrace class:

    try
    {
        throw new Exception();
    }
    catch (Exception ex)
    {
        // Get stack trace for the exception with source file information
        var st = new StackTrace(ex, true);
        // Get the top stack frame
        var frame = st.GetFrame(0);
        // Get the line number from the stack frame
        var line = frame.GetFileLineNumber();
    }
    

    Note that this will only work if there is a pdb file available for the assembly.

提交回复
热议问题