0

This is my WinForm solution entry point in Program.cs:

try
{
  Application.Run(new MainForm());
}
catch (Exception e)
{
  Log.error(e.ToString());
  ErrorHandlerForm abend = new ErrorHandlerForm(e);
  abend.ShowDialog();
}

It works fine, every exception thrown in my solution is gracefully handled!

But today I found an issue:

My program don't catch exceptions that occurs in UserControls construstors!

It simply crash to windows with the ugly system prompt (or it shows the error in the VisualStudio if i am in debug mode).

I don't understand this behaviour and I have no idea how to fix it, I want to catch those exception in my catch block.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Tara Rulez
  • 13
  • 1
  • 4

1 Answers1

0

This answer tries to explain the underlying problem.

Just add the following lines to your main method:

//Add the event handler for handling all unhandled UI thread exceptions to the event Application_ThreadException
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

and use this method to handle the exception:

/// <summary>
/// Handles all unhandled UI thread exceptions
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Threading.ThreadExceptionEventArgs"/> instance containing the event data.</param>
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
    //handle e.Exception here
}

It's also a good idea to handle all non-UI exceptions that were not catched explicitly. Just add the following:

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

where CurrentDomain_UnhandledException is your exception handler method.

Fabian
  • 781
  • 2
  • 8
  • 17