I have a test winforms app with ThreadExceptionHandler that displays a message box when an unhandled exception is caught, as follows:
[STAThread]
static void Main()
{
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
MessageBox.Show("error caught");
}
When I force an error in the ctor of Form 1 (e.g. dividebyzero) as follows:
public Form1()
{
InitializeComponent();
int i = 0;
int x = 5 / i;
}
and run the app outside of Visual Studio (in Windows 7), the divide by zero exception is not handled – I get an unhelpful “WindowsFormApplication1 has stopped working…” message.
However, when I move the dividebyzero exception to the Form1_Load event and rerun, the exception is handled properly.
Can someone explain why this is the case? The reason I ran this test program is because I am experiencing a similar unhandled exception issue in another, enterprise app that I am trying to track down.
This is probably due to the fact that the constructor is executed before
Application.Run()is called. Your code could also be written asYour thread exception handler only becomes active when
Application.Run()is executing. In order to catch exceptions in the form constructor, you need to surroundForm1 MyForm = new Form1();witch a seperate try/catch block.