Here's my hypothetical example. I have a very simple WPF window with a one Button. The Button.Click event has a handler that goes like this.
Action doit = () =>
{
Action error = () => { throw new InvalidOperationException("test"); };
try {
this.Dispatcher.Invoke(error, DispatcherPriority.Normal);
} catch (Exception ex) {
System.Diagnostics.Trace.WriteLine(ex);
throw;
}
};
doit.BeginInvoke(null, null);
I would expect that the exception would be caught and written down by the Trace.WriteLine
call. Instead, no exception is caught and the application breaks.
Does anybody knows of an possible explanation for this to happen? And what workaround do you suggest in order to catch exceptions thrown by the delegate invoked by Dispatcher.Invoke
?
Update 1: I put a throw
in the exception handling code. I don't want to actually ignore the exception. The whole point of my question is to handle it correctly. The problem is that the exception handling code is never executed.
Remember that this is an hypothetical example. My real code does not look like that. Also, assume that I can't change the code in the method to be invoked.
Update 2: Consider this similar example. Instead of a WPF window, I have a Windows Forms window. It has a button with the almost exactly the same handler. The only difference is in the invocation code. It goes like this.
this.Invoke(error);
In Windows Forms, the exception handling code is executed. Why the difference?