Feedback

C# - Unexpected Errors in Managed Applications

Veröffentlicht von am 3/4/2008
(1 Bewertungen)
Behandelt alle unbehandelten Exceptions einer Application
// see also
// [Unexpected Errors in Managed Applications]
// http://msdn.microsoft.com/msdnmag/issues/04/06/NET/default.aspx
namespace $MyNamespace${
   static class Program {
      public static void Main() {
         // try-catch innerhalb des Main:
         try {
            SetExceptionHandler();
            // Start application logic
            // Perhaps call to Application.Run(...);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMain());
         } catch (Exception e) {
            HandleUnhandledException(e);
         }
         // try-catch innerhalb des Main:
         try {
            SubMain();
         } catch (Exception e) {
            HandleUnhandledException(e);
         }
      }
   
      public static void SetExceptionHandler() {
         // Setup unhandled exception handlers
         AppDomain.CurrentDomain.UnhandledException += // CLR
            new UnhandledExceptionEventHandler(OnUnhandledException);
   
         Application.ThreadException += // Windows Forms
            new System.Threading.ThreadExceptionEventHandler(
                OnGuiUnhandedException);
      }
   
      // CLR unhandled exception
      private static void OnUnhandledException(Object sender,
         UnhandledExceptionEventArgs e) {
         HandleUnhandledException(e.ExceptionObject);
      }
   
      // Windows Forms unhandled exception
      private static void OnGuiUnhandedException(Object sender,
         ThreadExceptionEventArgs e) {
         HandleUnhandledException(e.Exception);
      }
   
      static void HandleUnhandledException(Object o) {
         Exception e = o as Exception;
   
         if (e != null) { // Report System.Exception info
            Debug.WriteLine("Exception = " + e.GetType());
            Debug.WriteLine("Message = " + e.Message);
            Debug.WriteLine("FullText = " + e.ToString());
         } else { // Report exception Object info
            Debug.WriteLine("Exception = " + o.GetType());
            Debug.WriteLine("FullText = " + o.ToString());
         }
   
         MessageBox.Show("An unhandled exception occurred " +
            "and the application is shutting down.");
         Environment.Exit(1); // Shutting down
      }
   }
}

Abgelegt unter Exception.

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!