【问题标题】:Prevent Winform to crash on unhandled exception防止 Winform 在未处理的异常上崩溃
【发布时间】:2014-03-09 23:22:12
【问题描述】:

我正在尝试以这种方式捕获未处理的异常:

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 捕获,我可以看到消息框弹出,但应用程序仍然崩溃说“程序已停止工作”。

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

【问题讨论】:

  • 通常你会在你的代码块周围加上一个 try - catch 块。异常将特定于可能发生的情况,如果你不确定就使用 Exception 类。
  • 我认为“停止工作”消息与另一个错误有关。
  • @Tejaswi Rana 如果我用 try-catch 块包围,那么它不再是未处理的异常,而是已处理,这显然不会使应用程序崩溃,但这不是我的问题。跨度>
  • @Xenolightning 没有这个属性,请自行查看:msdn.microsoft.com/en-us/library/…
  • @Mauren 我用上面的代码做了一个新项目,没有别的

标签: c# .net winforms exception-handling .net-4.5


【解决方案1】:

请参阅this stackoverflow question 了解有关捕获未处理异常的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    相关资源
    最近更新 更多