Handling Multiple Exception in a Task

 29-Oct-2014   nityaprakash     TPL  Exception-Handling    Comments  0

When we are expecting more than one exception in a set of task than we have Handle() delegate provided by AggregateException. We can provide our implementation to Handle method. This will be executed for each exception returned in AggregateException. AggregateException exposes a property InnerExceptions which is a collection exception thrown by each Task. Lets take a look to example:


        static void Main(string[] args)
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;

            Task t1 = new Task(() =>
            {
                Thread.Sleep(2000);
                throw new OperationCanceledException(token);
            }, token);

            Task t2 = new Task(() =>
            {
                throw new NullReferenceException();
            });

            t1.Start();
            t2.Start();

            try
            {
                Task.WaitAll(t1, t2);
            }
            catch (AggregateException ex)
            {
                ex.Handle((e) =>
                {
                    if (e is OperationCanceledException)
                    {
                        Console.WriteLine(string.Format("Task {0} : Operation Canceled. ", e.Source));
                    }
                    else if (e is NullReferenceException)
                    {
                        Console.WriteLine(string.Format("Task {0} : Null Reference Exception", e.Source));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Task {0} : Unknown Exception", e.Source));
                    }

                    return true;
                });
            }

            Console.WriteLine("Main Method is completed. Press enter to finish.");
            Console.ReadLine();
        }


In this case we are handling specific exception and unknown exception both here in Handle(). This method is returning true, it means exception are handled in this case.

If we don't want to handle the specific exception or unknown exception here and want to handle somewhere else than this method should return false.

This method will show below output:


Download Code
Nitya Prakash Sharma has over 10 years of experience in .NET technology. He is currently working as Senior Consultant in industry. He is always keen to learn new things in Technology and eager to apply wherever is possible. He is also has interest in Photography, sketching and painting.

My Blog
Post Comment

COMMENTS