zoukankan      html  css  js  c++  java
  • 处理Application.ThreadException异常, 拦截GUI主线程的异常

     .Net Winform有着自己的未处理异常机制。 Winform内部的代码会在Applicatin.Run方法里面为消息循环创建一个大的try...catch。 这样, 任何在GUI主线程里面的异常都会被这个try...catch所捕捉到, 这个默认的未处理异常handler会提取异常的所有信息然后显示在一个错误对话框里面,接着程序就中止了。这样我的try...catch就没有作用了,即下面的捕捉异常的代码是无效的。
    static void Main()
    {
        try
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new mainfrm());
        }
         catch(Exception e)
        {
            MessgaeBox.Show(e.Message);
        }
    }
     
    对于这个问题,可以处理Application.ThreadException异常,这样就可以拦截GUI主线程里面的异常了:

            static void Main()
            {
                //// Setup unhandled exception handlers
                //AppDomain.CurrentDomain.UnhandledException += // CLR
                //   new UnhandledExceptionEventHandler(OnUnhandledException);

                Application.ThreadException += // Windows Forms
             new System.Threading.ThreadExceptionEventHandler(
                 OnGuiUnhandedException);


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

            //// CLR unhandled exception
            //private static void OnUnhandledException(Object sender,
            //   UnhandledExceptionEventArgs e)
            //{
            //    HandleUnhandledException(e.ExceptionObject);
            //}

            // Windows Forms unhandled exception
            private static void OnGuiUnhandedException(Object sender,
               ThreadExceptionEventArgs e)
            {
                HandleUnhandledException(e.Exception);
            }

            static void HandleUnhandledException(Object o)
            {
                Exception e = o as Exception;

                if (e != null)
                { // Report System.Exception info
                    MessageBox.Show("Exception = " + e.GetType());
                    MessageBox.Show("Message = " + e.Message);
                    MessageBox.Show("FullText = " + e.ToString());
                }
                else
                { // Report exception Object info
                    MessageBox.Show("Exception = " + o.GetType());
                    MessageBox.Show("FullText = " + o.ToString());
                }

                MessageBox.Show("An unhandled exception occurred " +
                   "and the application is shutting down.");
                Environment.Exit(1); // Shutting down
            }

    上述状态是编译成EXE后调试的结果,在IDE环境中情况不同。

  • 相关阅读:
    安装devstack之配置proxy
    设备信息表项目
    好的运维工程师
    rhel 6.4 增加光盘为yum repo
    深度运维产品工具关键词
    坚持是一种能力
    书单 电影单 电视剧单
    三日不读书,便觉得言语无味,面目可憎
    STAR法则
    【断舍离】
  • 原文地址:https://www.cnblogs.com/littleCode/p/3974956.html
Copyright © 2011-2022 走看看