UnhandledException & ThreadException

Source: Internet
Author: User

When developing windows/console applications using. Net, it is recommended to catch the following two exceptions:

  • AppDomain. CurrentDomain. UnhandledException
  • Application. ThreadException

If there are some uncaught exceptions raised in a app-domain, the system default handler will report the exception and terminates the application by default. and if raised in a thread, the thread may be blocked. catchingUnhandledExceptionAndThreadExceptionEvents provides us a way of creating robust applications.

The following code segements demonstrate how to make use of the two events:

static void Main(){  try {   // Setup unhandled exception handlers   AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);   // Unhandled Forms exceptions will be delivered to our ThreadException handler   Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(AppThreadException);   // Other code   ....  }  catch( Exception e ) {    ....  }}/// <summary>/// CLR unhandled exception/// </summary>private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs e){  HandleUnhandledException(e.ExceptionObject);}/// <summary>/// Displays dialog with information about exceptions that occur in the application./// </summary>private static void AppThreadException(object source, System.Threading.ThreadExceptionEventArgs e){  HandleUnhandledException(e.Exception);}private static void HandleUnhandledException(Object o){  Exception exp = o as Exception;  MessageBox.Show(exp.Message, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);  Application.Exit(); // Shutting down}

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.