0
   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它不会显示“大错误...”消息框,而是告诉我没有异常处理程序。任何建议,将不胜感激。

4

1 回答 1

2

你需要UnhandleExceptionMode设置CatchException

       /* 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()方法。其中任何未处理的异常都将终止应用程序。

于 2013-02-13T03:26:25.893 回答