Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background worker exception handling

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"?

like image 203
mHelpMe Avatar asked Dec 14 '13 10:12

mHelpMe


People also ask

What is exception handling in c3?

An exception is defined as an event that occurs during the execution of a program that is unexpected by the program code. The actions to be performed in case of occurrence of an exception is not known to the program. In such a case, we create an exception object and call the exception handler code.

What is exception handling in .NET framework?

NET Framework, an exception is an object that inherits from the System. Exception class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the call stack to a place where the application provides code to handle the exception.

What are the four keywords for exception handling?

C# exception handling is built upon four keywords: try, catch, finally, and throw.

What is exception handling in AWP?

Exception handling is an in-built mechanism in . NET Framework to detect and handle run time errors. Exceptions are defined as anomalies that occur during the execution of a program. The . NET Framework provides a rich set of standard exceptions that are used during exceptions handling.


1 Answers

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

like image 155
Sergey Berezovskiy Avatar answered Oct 10 '22 17:10

Sergey Berezovskiy