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

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

    Here's a rather easy way to get a bunch of info from the Exception object: Just add code like this to any potentially exception-throwing methods:

    catch (Exception ex)
    {
        String exDetail = String.Format(ExceptionFormatString, ex.Message, Environment.NewLine, ex.Source, ex.StackTrace);
        MessageBox.Show(exDetail);
    }
    

    The information you get will often be more specific, especially as regards line numbers of where problems are occurring, than you would otherwise see.

    You may have noted that the String.Format() uses a constant, namely "ExceptionFormatString". This is a good practice, so that if you want to change it, after adding the above code to 40-eleven methods, you can just change it one place. Anyway, here it is:

    public static readonly String ExceptionFormatString = "Exception message: {0}{1}Exception Source: {2}{1}Exception StackTrace: {3}{1}";
    

    Happy Debugging!

提交回复
热议问题