繁体   English   中英

防止Winform在未处理的异常上崩溃

[英]Prevent Winform to crash on unhandled exception

我试图通过这种方式捕获未处理的异常:

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();

        }

异常被UnhandledExceptionEventHandler捕获,我可以看到弹出的消息框,但应用程序仍然崩溃说“程序已停止工作”。

如何在发生异常后保持应用程序运行?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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