问题描述
我正在使用以下代码来处理程序中所有未处理的异常.但是这个问题没有传播到指定的方法.
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);
}
FormMain有一个backgroundWorker对象.这个背景工作人员是负责大部分应用程序工作的人员,并且如果doWork方法中存在异常,则它不会像我期望的那样传播.这是我在MainForm中使用的backgroundworker的代码.
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..
谢谢
推荐答案
这是设计使然,BackgroundWorker类捕获在DoWork事件处理程序中引发的所有异常.并在RunWorkerCompleted事件处理程序的e.Error属性中公开它.所以这样写:
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..
}
这篇关于未处理的异常未在C#中捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!