WinForms Global Exception Handling?

后端 未结 7 1286
甜味超标
甜味超标 2020-11-27 05:17

I have implemented a software which have a DLL library which contains a huge set of classes which includes all the methods for my software.

Now i want to be able to

相关标签:
7条回答
  • 2020-11-27 05:51

    First, You should add:

    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
    

    After that You can catch exceptions, for example:

    [STAThread]
        static void Main()
        {
    
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += ApplicationThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
    
            if (DataBaseMNG.Init())
            {
                Application.Run(new MainForm());
            }
        }
    
        /// <summary>
        /// Global exceptions in Non User Interfarce(other thread) antipicated error
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var message =
                String.Format(
                    "Sorry, something went wrong.\r\n" + "{0}\r\n" + "{1}\r\n" + "please contact support.",
                    ((Exception)e.ExceptionObject).Message, ((Exception)e.ExceptionObject).StackTrace);
            MessageBox.Show(message, @"Unexpected error");
        }
    
        /// <summary>
        /// Global exceptions in User Interfarce antipicated error
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
        {
            var message =
                String.Format(
                    "Sorry, something went wrong.\r\n" + "{0}\r\n" + "{1}\r\n" + "please contact support.",
                    e.Exception.Message, e.Exception.StackTrace);
            MessageBox.Show(message, @"Unexpected error");
        }
    
    0 讨论(0)
提交回复
热议问题