I have a WPF app that has a WindowsFormsHost in which a 3rd party WinForms control is hosted. Sometimes, because of a bug in the 3rd party WinForms control I get a NullReferenceException
.
Although I had set up a DispatcherUnhandledException
handler I can't catch the exception there and continue the execution.
Only in the AppDomain.CurrentDomain.UnhandledException
handler I can "catch" it but I cannot do much from then on, the application simply exits.
Then I found a stackoverflow question (with an answer; can't find it now) which stated to try to do this :
System.Windows.Forms.Application.ThreadException += (sender, args) => { /* Catch it here */};
System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
That didn't help either because the (inline) handler did not get called ever.
Am I going the wrong way?
I am not sure why that handler never gets called in your case, probably because the exception was not thrown on a Windows Forms thread (the thread on which your forms and controls have been created), but generally, setting up handlers for DispatcherUnhandledException
, AppDomain.UnhandledException
and/or Application.ThreadException
doesn't allow you to prevent the termination of the process. They are event handlers, not exception handlers. The unhandled exception is still an unhandled exception even if you have setup those event handlers. Usually they are used to add some final logging or present a meaningful message to the user. Once an unhandled exception is raised there is nothing you can do to prevent the termination of the process.
Maybe the exception thrown is a CSE (Corrupted State Exception). To handle these kinds of exceptions, use [HandleProcessCorruptedStateExceptions] attribute for that function.