简体   繁体   English

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

[英]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". 异常被UnhandledExceptionEventHandler捕获,我可以看到弹出的消息框,但应用程序仍然崩溃说“程序已停止工作”。

How do I keep the application runnning after an exceptions occurs ? 如何在发生异常后保持应用程序运行?

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

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

相关问题 .NET 通用主机:防止应用程序因未处理的异常而崩溃 - .NET Generic Host : Prevent application crash on unhandled exception 如何在未处理的异常上崩溃 - How to crash on unhandled Exception Windows Forms 未处理的异常崩溃 - Windows Forms Unhandled Exception Crash 如何在未处理的任务异常上崩溃? - How to crash on unhandled Task exception? c#winform文本框验证未处理的异常 - c# winform textbox Validating unhandled exception 未处理的异常会使WCF服务崩溃吗? - unhandled exception will make WCF service crash? 如果后台线程中有未处理的异常,如何使主进程崩溃 - how to crash the main process if there is unhandled exception inside background thread 为什么后台线程中未处理的异常不会导致应用程序域崩溃? - Why unhandled exception in a background thread doesnt crash the app domain? C#应用程序中未处理的异常会导致应用程序崩溃吗? - Unhandled exception in C# application does it crash the app? Xamarin使用Prism导致Autofac崩溃而形成DependencyService-未处理的异常 - Xamarin Forms DependencyService with Prism with Autofac crash - Unhandled Exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM