How can I get the line number which threw exception?

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

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

相关标签:
12条回答
  • 2020-11-27 09:50

    Simple way, use the Exception.ToString() function, it will return the line after the exception description.

    You can also check the program debug database as it contains debug info/logs about the whole application.

    0 讨论(0)
  • 2020-11-27 09:51

    I tried using the solution By @davy-c but had an Exception "System.FormatException: 'Input string was not in a correct format.'", this was due to there still being text past the line number, I modified the code he posted and came up with:

    int line = Convert.ToInt32(objErr.ToString().Substring(objErr.ToString().IndexOf("line")).Substring(0, objErr.ToString().Substring(objErr.ToString().IndexOf("line")).ToString().IndexOf("\r\n")).Replace("line ", ""));
    

    This works for me in VS2017 C#.

    0 讨论(0)
  • 2020-11-27 09:52

    Check this one

    StackTrace st = new StackTrace(ex, true);
    //Get the first stack frame
    StackFrame frame = st.GetFrame(0);
    
    //Get the file name
    string fileName = frame.GetFileName();
    
    //Get the method name
    string methodName = frame.GetMethod().Name;
    
    //Get the line number from the stack frame
    int line = frame.GetFileLineNumber();
    
    //Get the column number
    int col = frame.GetFileColumnNumber();
    
    0 讨论(0)
  • 2020-11-27 09:54

    Extension Method

    static class ExceptionHelpers
    {
        public static int LineNumber(this Exception ex)
        {
            int n;
            int i = ex.StackTrace.LastIndexOf(" ");
            if (i > -1)
            {
                string s = ex.StackTrace.Substring(i + 1);
                if (int.TryParse(s, out n))
                    return n;
            }
            return -1;
        }
    }
    

    Usage

    try
    {
        throw new Exception("A new error happened");
    }
    catch (Exception ex)
    {
        //If error in exception LineNumber() will be -1
        System.Diagnostics.Debug.WriteLine("[" + ex.LineNumber() + "] " + ex.Message);
    }
    
    0 讨论(0)
  • 2020-11-27 10:00

    It works:

    var LineNumber = new StackTrace(ex, True).GetFrame(0).GetFileLineNumber();
    
    0 讨论(0)
  • 2020-11-27 10:01

    Working for me:

    var st = new StackTrace(e, true);
    
    // Get the bottom stack frame
    var frame = st.GetFrame(st.FrameCount - 1);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();
    var method = frame.GetMethod().ReflectedType.FullName;
    var path = frame.GetFileName();
    
    0 讨论(0)
提交回复
热议问题