Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am slightly confused on how to deal with an exception.

I have a background worker thread that runs some long running process. My understanding is if an exception occurs on the background worker thread the code will still end up at the RunWorkerCompleted method.

void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {

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

If this is the case is there any point in putting a try catch block around the bgWorker.RunWorkerAsync(); call, I assume not?

I want to rethrow the exception that is caught in the RunWorkerCompleted method, how can I do this without losing the stack trace - is what I have above correct? I read that you when rethrowing an exception you should just use "throw"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
318 views
Welcome To Ask or Share your Answers For Others

1 Answer

I suggest you to create some business specific exception, which describes operation which you were doing in background. And throw this exception with original exception as inner exception:

private void bgWorker_RunWorkerCompleted(
    object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Error != null)
        throw new BusinessSpecificException("Operation failed", e.Error);
    // ...
}

Thus original exception with its stack trace will be available, and you'll have more descriptive exception thrown.

Note - if you don't want to create new exception class, you can use existing ApplicationException or Exception. But its not that informative and if you are going to catch it somewhere, then you'll not be able to catch this particular exception only


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...