views:

389

answers:

3

I have an application that is mixed Winforms and WPF. In Winforms, I have a global exception handler that is defined as follows:

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.ThreadException += Application_ThreadException;

This ALWAYS catches exceptions anywhere in my application that occur that are not expected and handled gracefully.

For WPF, all I seem to be able to capture is:

 wpfAppDomain = new System.Windows.Application();
 wpfAppDomain.DispatcherUnhandledException +=
         wpfAppDomain_DispatcherUnhandledException;

This does NOT always catch global exceptions, and I often find that exceptions are swallowed somewhere and I'm not sure why.

How can I make a global exception handler for WPF that can catch any exception that occurs that is unhandled?

+1  A: 

There are several cases where this code will not catch an exception and do so by design

  • The exception is simply uncatchable. For example a runtime thrown StackOverflowException
  • The exception is unhandled in your code, but caught in the core WPF framework.

There is no way to catch all thrown exceptions. To do so would allow you to violate semantics of code that should always work.

JaredPar
I understand that not everything is catchable, nor should it be, but a good example would be a SQL Exception. The winform code catches all of them, but WPF seems to swallow them.
Russ
A: 

Have you tried this after calling SetUnhandledExceptionMode? Like this:

// Force all exceptions through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Charlie
A: 

DispatcherUnhandledException only catches exception from code called by a dispatcher (like the name suggests), it is supposed to catch exceptions thrown when called from WPF code.

It does not cover exceptions thrown from: WinForms, BackgroundWorker, the thread pool or threads you started yourself.

you can still use AppDomain.CurrentDomain.UnhandledException to catch those.

Nir