Alex Rivera | Logout

WPF ShowDialog swallowing exceptions during window load

Asked 2011-01-26T16:33:43.473
13

A WPF window dialog is shown using the ShowDialog method in the Window class like when a button is pressed on the main window, like this.

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var window = new Window1();
                window.ShowDialog();
            }
            catch (ApplicationException ex)
            {
                MessageBox.Show("I am not shown.");
            }
        }

The window has a Loaded event subscribed in the xaml like this:

<Window x:Class="Stackoverflow.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Loaded="Window_Loaded">
    <Grid />
</Window>

An exception is thrown in the Window_Loaded event

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        throw new ApplicationException();
    }

However the exception is not catched by the catch around the ShowDialog call, nor does the call return. The exception is swallowed and the window still displayed.

Why does this happen and how would I go about handling an exception in the Window_Loaded event of a WPF window? Do I have to catch it in the event-handler and Dispose the window manually?

In WinForms you need to call Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException)

in order to let exceptions bubble through ShowDialog calls. Is there a similar switch that needs to be set on WPF?

Edit
Report

1 Answer

1

Researching this a bit more I found this peculiar blogg entry describing a similar problem.

https://web.archive.org/web/20160313233937/https://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/

As it turns out it might be a 64-bit processor architecture problem. Who would have guessed?! It might explain why some people could not reproduce the issue my simple example. I tried to compile my example in "Any CPU", x64 and x86 but to no avail. On x64 the whole thing actually blew up completely crashing with a windows crash dialog.

So I guess this is the answer without verifying it on a 32-bit machine.

answered 2011-02-16T07:56:30.250

Your Answer