1
votes

We've been using unhandled exceptions for ages and we register both Application.Current.DispatcherUnhandledException and AppDomain.CurrentDomain.UnhandledException but the following repro case using Drop Event handler does not trigger any unhandled exception handler.

When I throw the exception from UI or task, some handler will be triggered, but form the documentation I don't comprehend why no handler is triggered in my scenario below as I would expect the Dispatcher calling DispatcherUnhandledException

This is VS 2015 with .net 4.5.2

Repro WPF code is very simple, only AllowDrop and Drop handler. Note: The handlers are registered in the window ctor, same behaviour when doing that in app.xaml.cs.

Just drag & drop any file into it, a message box should appear but it does not.

<Window x:Class="unhandledex_wpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" AllowDrop="True" Drop="MainWindow_OnDrop">
    <Grid>

    </Grid>
</Window>

Code behind:

using System;using System.Threading.Tasks;using System.Windows;

namespace unhandledex_wpf
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Application.Current.DispatcherUnhandledException += ( sender, args ) => MessageBox.Show( "Exception" );
            AppDomain.CurrentDomain.UnhandledException += ( sender, args ) => MessageBox.Show( "Exception" );
            TaskScheduler.UnobservedTaskException += ( sender, args ) =>  MessageBox.Show( "Exception" );

            // works Task.Run( ( )=> { throw new Exception( "foo" ); } );
        }

        private void MainWindow_OnDrop( object sender, DragEventArgs e )
        {
            throw new NotImplementedException("Catch me");
        }
    }
}
1

1 Answers

1
votes

If you want to handle an exception during a drop event you must handle it within your Drop event handler. Please refer to Peter Ritchie's answer in the following thread on the MSDN forums for more information about why: https://social.msdn.microsoft.com/Forums/windows/en-US/8beb1aba-1699-46c7-84dc-38768c7a21f6/treeview-dragdrop-event-ignores-exceptions-help?forum=winforms

Jay Wang (MSFT) has confirmed this in the WPF forum: https://social.msdn.microsoft.com/Forums/vstudio/en-US/a336acc8-5a29-45aa-b84a-8e235a0f838a/wpf-drop-event-hides-thrown-error?forum=wpf