Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continuing execution in WPF app after an exception in a hosted Winforms control

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?

like image 897
Andrei Rînea Avatar asked Oct 23 '22 09:10

Andrei Rînea


1 Answers

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.

like image 105
bitbonk Avatar answered Oct 30 '22 14:10

bitbonk