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

前端 未结 10 936
轮回少年
轮回少年 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:53

    Copy the entire stack trace in to a string or stringbuilder by using try/catch that can throw, see the below example

    try
    {
        //Do some programming
    }
    catch(Exception ex)
    {
    
       //Catch the exception and assign the stack trace
       StackTrace = ex;
    }
    

    The output will be

    System.IndexOutOfRangeException: Index was outside the bounds of the array.   
    at Program.Run() in C:\Console Application1\Program.cs:line 37    
    at Program.Main(String[] args) in C:\Console Application1\Program.cs:line 45 
    

    The first line shows the type of the exception and the message. The second line shows the file, function and line number where the exception was thrown

提交回复
热议问题