C# 为什么App.dispatchernhandledException处理程序不';无法捕获应用构造函数引发的异常?

C# 为什么App.dispatchernhandledException处理程序不';无法捕获应用构造函数引发的异常?,c#,wpf,exception,C#,Wpf,Exception,请查看以下代码: public partial class App : Application { public App():base() { this.DispatcherUnhandledException += App_DispatcherUnhandledException; throw new InvalidOperationException("exception"); }

请查看以下代码:

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;
        }
}

为什么处理程序不捕获应用程序构造函数引发的异常?

我也用这种方法来处理

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;

        }
}

无法构造应用程序的实例,因此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());
}
为什么处理程序不捕获
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
}
[STAThread]
静态void Main(字符串[]参数)
{
应用程序=新应用程序()//