0

This dialog ("Unhandled exception has occurred in your application.") will pop up sometimes, and sometimes not.

How to control whether to pop up or not, or is it possible to control?

And what's its default behavior (when and what exceptions to pop up)?

enter image description here

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
SE12938683
  • 196
  • 1
  • 7
  • 2
    Does this answer your question? [WinForms Global Exception Handling?](https://stackoverflow.com/questions/8148156/winforms-global-exception-handling) – Sathish Guru V Aug 08 '23 at 08:20
  • 3
    It should actually _never_ pop up. If you see this, you have failed to properly handle an exception in your application. – PMF Aug 08 '23 at 08:24
  • @SathishGuruV No, I just want to know about the dialog. – SE12938683 Aug 08 '23 at 08:26

2 Answers2

2

By default the dialog will pop up when there is an exception thrown on the UI thread (main thread IOW) and the exception is unhandled by your code. It won't pop up if the exception is thrown on other threads.

You can overwrite the default behaviour by using either the Application.SetUnhandledExceptionMode method:

// Your application will exit when there's an exception.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

Or the Application.ThreadException event:

// Nothing will happen unless the exception is re-thrown from the handler.
Application.ThreadException += (sender, e) => { };
shingo
  • 18,436
  • 5
  • 23
  • 42
1

From the documentation of the UnhandledException Event

Starting with the .NET Framework 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.

My guess is that the dialog uses this event, and that the type of exception may be the reason. You can check the event log to investigate the type of exceptions that occur, and there might be some pattern you could discern.

But this should be a pants-on-fire situation. Whatever the reason for the crashes are you need to fix it. Some exceptions may need to be handled with try/catch, while others should never occur in the first place. Relying on some error dialog provided by the framework, for anything, is not a good idea.

JonasH
  • 28,608
  • 2
  • 10
  • 23