Jeff Dege
Jeff Dege

Reputation: 11700

WPF - Exceptions not caught?

I'm trying to implement a login window, in WPF.

I have a MainWindow.xaml:

<Window ...
    Closing="Window_Closing">
    ...

And then in MainWindow.xaml.cs:

private void Window_Loaded(object sender, RoutedEventArgs e) {
    LoginWindow loginWindow = new LoginWindow();
    loginWindow.Owner = this;
    loginWindow.ShowDialog();
    ...

In the LoginWindow constructor I'm throwing an exception. It's never caught.

If I wrap the contents of Window_Loaded in a try/catch block, I can catch the exception, but if I rethrow it, from within Window_Load(), it's never caught.

This seems very odd, to me. I guess I'm used to environments where uncaught exceptions kill the app. Is there something I need to do to enable this, in WPF?

Upvotes: 1

Views: 315

Answers (1)

Gayot Fow
Gayot Fow

Reputation: 8792

Using this construct will restore the exception to visibility and allow you to catch it in the CurrentDomain_UnhandledException method on an x86 build...

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        Loaded -= MainWindow_Loaded;
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        Dispatcher.BeginInvoke(DispatcherPriority.Loaded, (SendOrPostCallback) delegate
        {
            Login l = new Login {Owner = this};
            l.ShowDialog();
        }, new object[] {null});
    }

Upvotes: 2

Related Questions