How to get error line number of code using try-catch

前端 未结 10 940
轮回少年
轮回少年 2020-12-05 13:08

I want to get line number of code which cause error. For example;

static void Main(string[] args)
{
    using (SqlConnection conn = new SqlConnection(bagcum)         


        
10条回答
  •  爱一瞬间的悲伤
    2020-12-05 14:03

    The problem is that you're trying to get the line number of the first frame of the exception:

    System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
    Console.WriteLine("Line: " + trace.GetFrame(0).GetFileLineNumber());
    

    However, the exception does not originate in the line you write ExecuteNonQuery, but somewhere within that function, possibly multiple stack frames (i.e. nested function calls) deeper. So the first frame (which you explicitly retrieve using GetFrame(0)) is somewhere inside Microsoft's code (most likely System.Data.dll) for which you don't have any debugging symbols.

    Write out the complete exception stacktrace in your function to see what I mean:

    try
    {
       // your code ...
    }
    catch (Exception ex) 
    {
       Console.WriteLine(ex);
    }
    

    Short of parsing the stacktrace (i.e. ex.StackTrace) there is no reliable why to get the linenumber of the "ExecuteNonQuery()" invocation. I would especially not try to count the stackframes up the stack where your call to ExecuteNonQuery() happens.

    I wonder however, what you need the sole linenumber for, why not just log/print/whatever the complete stacktrace instead. At least for diagnostics reasons that is much more useful anyway.

提交回复
热议问题