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

前端 未结 10 928
轮回少年
轮回少年 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 13:41

    You can use the System.Diagnostics.StackTrace class as below:

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

提交回复
热议问题