Tamerlane February 2016

Catch exception thrown while task execution in anonymous method

I have a code similar to this :

class A
{
    public Action<int, int> OnAddition;

    public int Add(int val1, int val2)
    {
        if (OnAddition != null)
        {
            OnAddition(val1, val2);
        }

        return val1 + val2;
    }
}

class B
{
    A a = new A();

    public B()
    {
        a.OnAddition = (v1, v2) =>
        {
            Task.Run(() =>
            {
                Console.WriteLine("Adding {0} and {1}", v1, v2);
                throw new Exception("Blah");
            });
        };
    }

    public int Add(int val1, int val2)
    {
        return a.Add(val1, val2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        try
        {
            B b = new B();

            Console.WriteLine(b.Add(1, 7));
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

I have no control over the classes A and B and the problem is that when throw new Exception("Blah"); happens my code is not able to catch the exception.

How can my code catch that Exception ?

Answers


Servy February 2016

Since you have no control over the classes, there's no possible way for you to catch the exception. You're throwing the exception after you've already finished invoking the event, so you've already (at least potentially) left the try block by the time the event is thrown. The event would need to be specifically designed to support handling errors of asynchronous method handlers to be able to handle such an exception.


i3arnon February 2016

You can't. If you can't change the code for these classes you can't catch that exception.

You can however be notified about it by subscribing to the TaskScheduler.UnobservedTaskException event that will be raised when the GC collects that task.

Post Status

Asked in February 2016
Viewed 1,525 times
Voted 12
Answered 2 times

Search




Leave an answer