简体   繁体   中英

Prevent Winform to crash on unhandled exception

I'm trying to catch unhandled exception this way :

static class Program
{
        [STAThread]
        static void Main(string[] args)
        {
            Application.ThreadException += new ThreadExceptionEventHandler(Program.ThreadExceptionEventHandler);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Program.UnhandledExceptionEvent);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        public static void UnhandledExceptionEvent(Object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show("UnhandledExceptionEvent", "UnhandledExceptionEvent");
        }

        public static void ThreadExceptionEventHandler(Object sender, ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message, "ThreadExceptionEventHandler");
        }
}

private void button1_Click(object sender, EventArgs e)
        {
            //Execute method on a new thread
            new Thread(delegate()
            {
                //Do stuff ...
                throw new Exception("Some random unhandled exception");

            }).Start();

        }

The exception is caught by the UnhandledExceptionEventHandler, I can see the message box popping, but the application still crashes saying "Program has stopped working".

How do I keep the application runnning after an exceptions occurs ?

有关捕获未处理的excpetions的信息,请参阅此stackoverflow问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM