c# UserControl constructor don't throws exceptions as expected


c# UserControl constructor don't throws exceptions as expected



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.





what error do you get in Visual studio when in debug mode ?
– Prany
Jul 1 at 17:13





1 Answer
1



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.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to make file upload 'Required' in Contact Form 7?

Rothschild family

amazon EC2 - How to make wp-config.php to writable?