The exception in the OnIdle event does not bubble

In my main form, I signed up for two events: Application.ThreadException and Application.Idle. Theoretically, any exception that was not caught should be a bubble up to its main form. However, this does not work if an exception occurs in the OnIdle event. The system just crashes. Does anyone know how to solve this problem? Thanks.

+4
source share
2 answers

I agree that it is not very logical not to receive a ThreadException event. However, it works this way, a ThreadException only occurs when a message loop sends an event, and there is an unhandled exception in the event handler. The Idle event occurs when a message is no longer sent; it follows a completely different code path.

You can get around this by throwing exceptions for your Idle event handler:

void Application_Idle(object sender, EventArgs e) { try { // Do stuff } catch (Exception ex) { Application.OnThreadException(ex); } } 

Beware that ThreadException is rather a mixed blessing if you allow the user to decide whether to quit or continue the program. Also note that for all exceptions in your program there is not enough versatility, you still need an AppDomain.CurrentDomain.UnhandledException to handle exceptions that occur in threads other than the user interface thread or exceptions that occur before the message loop starts work.

If you do this to make sure the user cannot click Continue, simply use Application.SetUnhandledExceptionMode () to completely disable the ThreadException event. Now everything goes through the AppDomain.UnhandledException. This is the best way.

+3
source

Exceptions only bubble the stack of called methods.

The Idle event is not raised from your form code and therefore will not bubble up to any of your code.

Instead, you have to catch unhandled exceptions.

Take a look at:

One of them will catch your exception.

0
source

Source: https://habr.com/ru/post/896578/


All Articles