'C# cannot catch Exception from within anonymous Action

I have an application in which I execute requests on a seperate thread while a waiting form is displayed. This is done using a Request class which executes an Action object.

Now of course i have some error-handling logic, which seems to catch errors twice, and i cannot figure why.

This is the code inside the Request class:

public virtual Tuple<string, string> ExecuteInternal()
    {
        ReturnValue<string> rv = new ReturnValue<string>();
        try
        {
            Executor.Invoke(rv);
            Response = rv.Value;
            return new Tuple<string, string>("Success", Response);
        }
        catch (Exception ex)
        {
            //-----------this gets triggered and correctly returns the "Failure" Tuple

            return new Tuple<string, string>("Failure", ex.ToString());
        }
    }

This is the code responsible for executing the requests one after another:

 new Thread(() =>
        {
            foreach (Request request in Requests)
            {
                string response = "";
                try
                {
                    Tuple<string, string> result = request.ExecuteInternal();
                    string status = result.Item1;
                    response = result.Item2;
                    UpdateStatus(request, status);
                }
                catch (Exception ex)
                {
                    //-------------------somehow this part gets also triggered

                    request.Response = ex.ToString() + "\n\n\n" + response;
                    UpdateStatus(request, "Failure2");
                }
            }
}).Start();

Now if i have an Exception inside the "Executor" which is an Action, eg.

Executor = () => { throw new Exception(); };

, the error handler inside the Request class returns a "Failure" tuple, so the exception handler works. BUT the exception handler inside the Thread also catches the same Exception somehow, and i cannot figure out why.



Solution 1:[1]

I fixed it, the "UpdateStatus" method was causing some issues.

It is supposed to call another Action inside the Request responsible for error handling in a user-friendly way, but due to a typo that variable was not getting initialized. It works properly now :)

I debugged everything line by line and traced it down that way. The exception was rethrown, since the error handler was not initialized as said above.

(This is a quite big project i 'inherited' and am still getting used to...)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 janek49