Task Parallel Library exception handling
- by user1680766
When handling exceptions in TPL tasks I have come across two ways to handle exceptions. The first catches the exception within the task and returns it within the result like so:
                            var task = Task<Exception>.Factory.StartNew(
                                () =>
                                    {
                                        try
                                        {
                                            // Do Something
                                            return null;
                                        }
                                        catch (System.Exception e)
                                        {
                                            return e;
                                        }
                                    });
                            task.ContinueWith(
                                r =>
                                    {
                                        if (r.Result != null)
                                        {
                                            // Handle Exception
                                        }
                                    });
The second is the one shown within the documentation and I guess the proper way to do things:
                                var task = Task.Factory.StartNew(
                                    () =>
                                        {
                                            // Do Something
                                        });
                                task.ContinueWith(
                                    r =>
                                        {
                                            if (r.Exception != null)
                                            {
                                                // Handle Aggregate Exception
                                                r.Exception.Handle(y => true);
                                            }
                                        });
I am wondering if there is anything wrong with the first approach? I have received 'unhandled aggregate exception' exceptions every now and again using this technique and was wondering how this can happen?