处理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环境中情况不同。

posted @ 2014-09-16 15:13  so...  阅读(1529)  评论(0编辑  收藏  举报