System.Windows.Forms.Control.Invoke重新引发InnerException

时间:2018-12-13 05:02:35

标签: c# winforms invoke

我有一个用Invoke调用的方法。此方法可以引发包含内部异常SecondException的异常FirstException。发生这种情况时,Invoke会抛出FirstException而不是SecondException

这是简化的代码。它打印TestApp.FirstException: First exception。为什么?如何防止拆开内部异常?

using System;

namespace TestApp
{
    public partial class Form : System.Windows.Forms.Form
    {
        public Form()
        {
            InitializeComponent();
        }

        private void Form_Shown(object sender, EventArgs e)
        {
            try
            {
                Invoke(new Action(DoSomething));
            }
            catch (Exception exception)
            {
                Invoke(new Action(() =>
                {
                    textBox.AppendText(exception.ToString());
                }));
            }
        }

        private void DoSomething()
        {
            var caughtException = new FirstException("First exception");
            throw new SecondException("Second exception", caughtException);
        }
    }

    public class FirstException : Exception
    {
        public FirstException(string message) : base(message) { }
    }

    public class SecondException : Exception
    {
        public SecondException(string message, Exception innerException) : base(message, innerException) { }
    }
}

0 个答案:

没有答案