Catching Unhandled Exceptions

Prabhukiran345
Posted by Prabhukiran345 under C# category on | Points: 40 | Views : 544
This example shows how to manage all exceptions that haven't been caught in the try-catch sections (in Windows Forms application).

The UnhandledException event handles uncaught exceptions thrown from the main UI thread.
The ThreadException event handles uncaught exceptions thrown from non-UI threads.

static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

Application.Run(new Form1());
}

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");
// here you can log the exception ...
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled UI Exception");
// here you can log the exception ...
}

Comments or Responses

Login to post response