1

I have a windows from application with a program.cs code like this:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ThreadException += (sndr, evnt) => 
        { 
            MessageBox.Show("An error occur. Please contact your administrator.\nError description: " + 
                evnt.Exception.Message + "\nStack trace:\n" + evnt.Exception.StackTrace, 
                evnt.Exception.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error); 
        };
        Application.Run(new frmLogin());
    }
}

But when an exception is thrown inside the BackgroundWorker.DoWork event, the Application.ThreadException didn't catch it.

How can the Application.ThreadException catch an exception from a different thread created by a BackgroundWorker?

I know catching errors in the Application.ThreadException is not a good practice but we only use it as our last level of error catching.

My code is in C#, framework 4, build in VS2010 Pro.

Please help. Thanks in advance.

John Isaiah Carmona
  • 5,260
  • 10
  • 45
  • 79
  • 1
    This question is a duplicate of http://stackoverflow.com/questions/4284986/c-sharp-catching-unhandled-exception-on-seperate-threads – Matt Varblow Feb 22 '12 at 05:48

2 Answers2

4

See this question: BackgroundWorker exceptions don't get propagated like that, so you can't catch them in ThreadException.

BackgroundWorkers that throw exceptions call RunWorkerCompleted as usual, but set the Error property on the event arguments.

Community
  • 1
  • 1
porges
  • 30,133
  • 4
  • 83
  • 114
1

The BackgroundWorker catches exception for you(will not expose to Application.ThreadException or AppDomain.UnhandledException) and pass the exception to argument of RunWorkerCompleted event. You will handle the exception on RunWorkerCompleted event handler.

There is RunWorkerCompletedEventArgs.Error that you can get the exception once the RunWorkerCompleted event fired.

    private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        { 
            // handle exception here
        }
    }
Pongsathon.keng
  • 1,417
  • 11
  • 14