This article Reprinted from: http://www.cnblogs.com/yinzixin/
Very useful article, thanks to yinzixin
-----------------------------------
If an uncaptured exception exists in the Windows Forms program, it will cause the program to crash and give the user a bad impression. For example, the following program simulates an uncaptured exception:
Button event:
private void button1_Click(object sender, EventArgs e)
{
throw new Exception();
}
Click Exception. The following default window is displayed.
Windows Forms provides two events to handle uncaptured exceptions, namely Application. threadException and AppDomain. unhandledException event. The former is used to handle exceptions in the UI thread, and the latter is used to handle exceptions in other threads. To enable the program to handle exceptions using custom events, use the following code:
Static class Program
{
/// <Summary>
/// The main entry point for the application.
/// </Summary>
[STAThread]
Static void Main ()
{
Application. ThreadException + = new System. Threading. ThreadExceptionEventHandler (Application_ThreadException );
AppDomain. CurrentDomain. UnhandledException + = new UnhandledExceptionEventHandler (CurrentDomain_UnhandledException );
Application. EnableVisualStyles ();
Application. SetCompatibleTextRenderingDefault (false );
Application. Run (new Form1 ());
}
Static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e)
{
MessageBox. Show ("sorry, your operation has not been completed. Please try again or contact the software provider ");
LogUnhandledException (e. ExceptionObject );
}
Static void Application_ThreadException (object sender, System. Threading. ThreadExceptionEventArgs e)
{
MessageBox. Show ("sorry, your operation has not been completed. Please try again or contact the software provider ");
LogUnhandledException (e. Exception );
}
Static void LogUnhandledException (object exceptionobj)
{
// Log the exception here or report it to developer
}
}
The result of running the program is as follows: