Ivan
Ivan

Reputation: 1

Why App.DispatcherUnhandledException handler doesn't catch exceptions thrown by App constructor?

Please look at the following code:

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

Why the handler doesn't catch the exception thrown by App constructor?

Upvotes: 0

Views: 1334

Answers (3)

mm8
mm8

Reputation: 169160

Why the handler doesn't catch the exception thrown by App constructor?

Simply because there is no dispatcher running before the App has been constructed.

This is the Main method that is generated for you by the compiler:

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

From the docs:

When Run is called, Application attaches a new Dispatcher instance to the UI thread. Next, the Dispatcher object's Run method is called, which starts a message pump to process windows messages.

You cannot call Run before the you have actually created the App object.

Upvotes: 1

El Barrent
El Barrent

Reputation: 174

Instance of App failed to construct, therefore Application.Current doesn't make any sense. You should subscribe on 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());
}

Upvotes: 0

mohammed mazin
mohammed mazin

Reputation: 445

I've worked this way to do the same.

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;

        }
}

Upvotes: 0

Related Questions