Tuesday, 8 January 2008

Use Application.ThreadException event to catch unhandled exceptions in a Windows Forms application

Application.ThreadException event occurs when an unhandled exception is thrown, based on MSDN. To avoid your Windows application from crashing when an exception is not caught by your code, you should attach your own event handler to this event in program.cs file.

The following code shows how this works:

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(UnHandledException);

Application.Run(new MainForm());
}

static void UnHandledException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
}

Note the event handler should be attached before the Application.Run method.

1 comment:

Jagna Co Kalani said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai.