user568551
user568551

Reputation: 449

Backgroundworker can't handle exception

I have a background worker that will throw an exception when there is a problem. I'm trying to catch the exception in the workcompleted event.
My code is roughly as follows:

void workerProcessReports_DoWork(object sender, DoWorkEventArgs e)
{    
    try
    {
      //Work is here.  The code here throws an exception

    }
    catch (Exception ex)
    {
        throw ex;
    }
}

void workerProcessReports_RunWorkerCompleted(object sender, 
                                             RunWorkerCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show("There was a problem");
    }
    else
    {
        MessageBox.Show("No Problems");                    
    }
}

The problem is that visual studio breaks on the throw ex in the dowork method with the Message

InvalidOperationException was unhandled by user code

What's going on?

Upvotes: 2

Views: 561

Answers (1)

JNYRanger
JNYRanger

Reputation: 7097

Don't catch and rethrow your same exception, that's a waste and causes your stack trace to get messed up.

If you want the exact same exception to be thrown after catching it from a parent exception type, just write throw; in your catch block. If you plan on just throwing everything anyway, don't bother catching it in the first place.

If you do allow your exception to occur without handling it in the doWork method, then you can throw on the parent thread in your RunWorkerCompleted method.

Within your RunWorkerCompleted method you can throw it as such:

if(e.Error != null)
{
    throw e.Error;
}

However, at this point if it's something you can handle you may just want to recover and continue, instead of throwing since you are already aware that an exception occured. Especially, if this parent thread is your UI thread, then this is the perfect opportunity to display an error message instead of throwing and potentially crashing your application for a non-fatal error.

Upvotes: 4

Related Questions