【问题标题】:Why App.DispatcherUnhandledException handler doesn't catch exceptions thrown by App constructor?为什么 App.DispatcherUnhandledException 处理程序不捕获 App 构造函数抛出的异常?
【发布时间】:2020-05-09 13:50:32
【问题描述】:

请看以下代码:

public partial class App : Application
{
        public App():base()
        {
                this.DispatcherUnhandledException += App_DispatcherUnhandledException;
                throw new InvalidOperationException("exception");
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
                MessageBox.Show(e.Exception.Message);
                e.Handled = true;
        }
}

为什么处理程序没有捕捉到 App 构造函数抛出的异常?

【问题讨论】:

标签: c# wpf exception


【解决方案1】:

我也是这样做的。

public partial class App : Application
{
        public App():base()
        {
                Application.Current.DispatcherUnhandledException += new
                   System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(
                      AppDispatcherUnhandledException);
                throw new InvalidOperationException("exception");
        }

void AppDispatcherUnhandledException(object sender,
           System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            //do whatever you need to do with the exception
            //e.Exception
              MessageBox.Show(e.Exception.Message);
                e.Handled = true;

        }
}

【讨论】:

    【解决方案2】:

    App 实例未能构造,因此 Application.Current 没有任何意义。您应该订阅 AppDomain.CurrentDomain.UnhandledException

    public App() : base()
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
        throw new InvalidOperationException("exception");
    }
    
    private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        MessageBox.Show(e.ExceptionObject.ToString());
    }
    

    【讨论】:

      【解决方案3】:

      为什么处理程序没有捕捉到App构造函数抛出的异常?

      仅仅是因为在App 被构造之前没有调度器运行。

      这是编译器为您生成的Main 方法:

      [STAThread]
      static void Main(string[] args)
      {
          App application = new App(); //<-- your throw here
          application.InitializeComponent();
          application.Run(); //<-- and there is no dispatcher until here
      }
      

      来自docs

      Run 被调用时,Application 将一个新的Dispatcher 实例附加到 UI 线程。接下来调用Dispatcher对象的Run方法,启动消息泵来处理windows消息。

      在您实际创建 App 对象之前,您不能调用 Run

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        • 1970-01-01
        • 2011-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多