. NET under Unhandled exception capture

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.