在winform中统一捕捉异常

=====================================
使用全局事件扑捉
=====================================
using System;
using System.Windows.Forms;

//注册全局的异常处理程序,扑获产生的异常。
namespace Zhengzuo.CSharpCode
{
    static class Program
    {
      
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        { 
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

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

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }
}

  不错的办法,这样可以像在web中使用Application_Error一样捕获所有的异常,但是在调试中似乎异常不能进入Application_ThreadException事件中,反而在CurrentDomain_UnhandledException事件中能够得到,但是如果直接运行生成好的exe文件在Application_ThreadException事件中异常又能够被正常捕获。

  谁知道原因,望高手赐教。

posted @ 2009-11-19 23:08  devotion  阅读(1094)  评论(0编辑  收藏  举报