How can I get the line number which threw exception?

后端 未结 12 2172
既然无缘
既然无缘 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: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);
    }
    

提交回复
热议问题