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

2

5

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?

Maness answered 21/9, 2012 at 14:56 Comment(0)
G
3

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.

Geophagy answered 24/9, 2012 at 10:44 Comment(1)
It seems that creating a new project (File->New->WPF Application) leads to the normal behavior (i.e.: The exception thrown in a WinForms component gets caught in the ThreadException handler). The original application that I'm working on has some strange/different behavior. I just need to find out WHY it's behaving differently.Virgina
T
0

Maybe the exception thrown is a CSE (Corrupted State Exception). To handle these kinds of exceptions, use [HandleProcessCorruptedStateExceptions] attribute for that function.

Tetanic answered 2/4, 2018 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.