Concurrent task library exception handling

When handling exceptions in TPL tasks, I came across two ways to handle exceptions. The first throws an exception inside the task and returns it as a result as follows:

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 in the documentation, and I think the right way to do something is:

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 something is wrong with the first approach? I got “unhandled aggregated exceptions” exceptions every time using this technique, and wondered how this could happen.

To clarify, I think the second template is better, but I have a piece of code that uses the first template, and I'm trying to figure out if it needs refactoring, i.e. if it turns out that not all exceptions will be caught.

+5
1

, . , "" . , . , "" (.. , Exception), , Exception Result. , ( ), catch (.. Handle).

.

+3
source

All Articles