C # handles unhandled exception in the following ways:
1. Add the following code to the main () method of the program.
Handling exceptions that are not handled by threads
Application.ThreadException + = new System.Threading.ThreadExceptionEventHandler (application_threadexception);
Handling exceptions that are not handled by the system
AppDomain.CurrentDomain.UnhandledException + = new Unhandledexceptioneventhandler (currentdomain_unhandledexception );
Run the program
Application.Run (New Frmservermain ());
2. Method:
static void Application_threadexception (object sender, System.Threading.ThreadExceptionEventArgs e)
{
String str = "";
Exception error = e.exception as Exception;
if (Error! = NULL)
{
str = string. Format ("Application unhandled exception.\nexceptiontype:{0}\nexception Message: {1}\n stacktrace:{2}\n",
Error. GetType (). Name, error. Message, error. StackTrace);
}
Else
{
str = string. Format ("Application Thread Exception msg:{0}", E);
}
Writeerrinfo (str);
}
static void Currentdomain_unhandledexception (object sender, UnhandledExceptionEventArgs e)
{
String str = "";
Exception error = E.exceptionobject as Exception;
if (Error! = NULL)
{
str = string. Format ("Application Unhandledexception:{0};\nstacktrace:{1}", error. Message, error. StackTrace);
}
Else
{
str = string. Format ("Application unhandlederror:{0}", E);
}
Writeerrinfo (str);
}
static void Writeerrinfo (String verrmsg)
{
using (System.IO.FileStream fs = new System.IO.FileStream (Application.startuppath + "\\Log\\TestException.log",
System.IO.FileMode.Append, System.IO.FileAccess.Write))
{
using (System.IO.StreamWriter w = new System.IO.StreamWriter (Fs,system.text.encoding.utf8))
{
W.writeline (VERRMSG); DateTime.Now.ToString ("Yyyy/mm/dd HH:mm:ss");
}
}
}
Detailed analysis can be found in:
Http://www.cnblogs.com/eaglet/archive/2009/02/17/1392191.html
. NET under Unhandled exception capture