Unhandled exception not caught in C#

房东的猫 提交于 2019-12-23 13:09:24

问题


I am using following code to handle all the unhandled exceptions in the program. But the problem that the exception is not propagated to the specified methods.

 [STAThread]
    static void Main()
    {


        AppDomain currentDomain = default(AppDomain);
        currentDomain = AppDomain.CurrentDomain;
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
        // Handler for unhandled exceptions.
        currentDomain.UnhandledException += GlobalUnhandledExceptionHandler;
        // Handler for exceptions in threads behind forms.
        System.Windows.Forms.Application.ThreadException += GlobalThreadExceptionHandler;


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

  private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
    {
        Exception ex = (Exception)e.ExceptionObject;        

        MessageBox.Show(ex.Message,
                                  "Important",
                                  MessageBoxButtons.YesNo);
    }

    private static void GlobalThreadExceptionHandler(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        Exception ex = e.Exception;

        MessageBox.Show(ex.Message,
                                 "Important",
                                 MessageBoxButtons.YesNo);

    }

The FormMain has a backgroundWorker object. This backgroundworker is the one who does most part of the app and if there is an exception in doWork method, it is not propogated as I expect it to .. Here is code for the backgroundworker that I use in my MainForm.

 private void button_startSync_Click(object sender, EventArgs e)
 {            
     backgroundWorker1.RunWorkerAsync(getSettings());\          
 }

  private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  {        

     // ... processing code
     // Unhandled Exception will generated in this method...           
  }

Please advise what am I doing wrong here, I want exceptions generated anywhere in my program being caught into those global handlers above, so that the erro/exceptions be reported back for fixing..

Thanks,


回答1:


This is by design, the BackgroundWorker class catches any exceptions that are thrown inside the DoWork event handler. And exposes it in the e.Error property in the RunWorkerCompleted event handler. So write it like this:

  private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
  { 
      if (e.Error != null) throw e.Error;
      // etc..
  }


来源:https://stackoverflow.com/questions/10463408/unhandled-exception-not-caught-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!