次のコードを使用して、プログラム内の未処理の例外をすべて処理しています。しかし、例外が指定されたメソッドに伝播されないという問題。
[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オブジェクトがあります。このbackgroundworkerはアプリの大部分を実行する人であり、doWorkメソッドに例外がある場合、期待どおりに伝播されません。..MainFormで使用するbackgroundworkerのコードを次に示します。
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...
}
ここで何が間違っているのかを教えてください。プログラムのどこかで生成された例外が上記のグローバルハンドラーにキャッチされ、エラー/例外が修正のために報告されるようにします。
ありがとう、