Application.ThreadException not working

本文关键字:working not ThreadException Application | 更新日期: 2023-09-27 17:59:06

   static class Program
   {
       [STAThread]
       static void Main()
       {
           /* From my understanding this should install the exception handler */
           Application.ThreadException += GetEventHandler();
           /* Since posting this question I have found that I need to add the 
              following line, but even with the following line in place the
              exceptions thrown are not caught.... */
           Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
           /* Some auto generated code here */
           Application.Run(new MyForm());
       }

       private static ThreadExceptionEventHandler GetEventHandler()
       {
           return new ThreadExceptionEventHandler(OnThreadException);
       }
       private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
       {
           MessageBox.Show("Big error...");
       }
   }

根据:http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception%28v=vs.71%29.aspx这应该行得通。但是当在MyForm类内部抛出异常时,它不会显示"Big error…"消息框,而是告诉我没有异常处理程序。如有任何建议,我们将不胜感激。

Application.ThreadException not working

您需要将UnhandleExceptionMode设置为CatchException it

       /* From my understanding this should install the exception handler */
       Application.ThreadException += GetEventHandler();
       Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
       /* Some auto generated code here */
       Application.Run(new MyForm());

Application.ThreadException只能捕获UI线程中引发的异常。在由于Windows通知而运行的代码中。或者用技术术语来说,是由消息循环触发的事件。大多数Winforms活动都属于这一类。

它所做的而不是陷阱是在任何非UI线程上引发的异常,例如以Thread.Start()ThreadPool.QueueUserWorkItem或委托的BeginInvoke()方法启动的工作线程。其中任何未处理的异常都将终止应用程序。