Incorrect stacktrace by rethrow

前端 未结 12 1392
不知归路
不知归路 2020-11-29 01:49

I rethrow an exception with \"throw;\", but the stacktrace is incorrect:

static void Main(string[] args) {
    try {
        try {
            throw new Exce         


        
12条回答
  •  情歌与酒
    2020-11-29 02:26

    Do you want your right line number? Just use one try/catch per method. In systems, well... just in the UI layer, not in logic or data access, this is very annoying, because if you need database transactions, well, they shouldn't be in the UI layer, and you won't have the right line number, but if you don't need them, don't rethrow with nor without an exception in catch...

    5 minutes sample code:

    Menu File -> New Project, place three buttons, and call the following code in each one:

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            Class1.testWithoutTC();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine + "In. Ex.: " + ex.InnerException);
        }
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            Class1.testWithTC1();
        }
        catch (Exception ex)
        {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine + "In. Ex.: " + ex.InnerException);
        }
    }
    
    private void button3_Click(object sender, EventArgs e)
    {
        try
        {
            Class1.testWithTC2();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine + "In. Ex.: " + ex.InnerException);
        }
    }
    

    Now, create a new Class:

    class Class1
    {
        public int a;
        public static void testWithoutTC()
        {
            Class1 obj = null;
            obj.a = 1;
        }
        public static void testWithTC1()
        {
            try
            {
                Class1 obj = null;
                obj.a = 1;
            }
            catch
            {
                throw;
            }
        }
        public static void testWithTC2()
        {
            try
            {
                Class1 obj = null;
                obj.a = 1;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
    

    Run... the first button is beautiful!

提交回复
热议问题