未处理的exception未在C#中捕获

我使用以下代码来处理程序中的所有未处理的exception。 但是exception没有传播到指定方法的问题。

[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); } 

FormMain有一个backgroundWorker对象。 这个背景工作者是应用程序的大部分工作者,如果在doWork方法中有exception,它就不会像我期望的那样传播。这是我在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... } 

请告诉我这里做错了什么,我希望我的程序中的任何地方生成的exception都被上面的那些全局处理程序捕获,以便报告错误/exception以进行修复。

谢谢,

这是设计使然,BackgroundWorker类捕获DoWork事件处理程序中引发的任何exception。 并在RunWorkerCompleted事件处理程序的e.Error属性中公开它。 所以这样写:

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