title: I want the Task to handle any exceptions that are thrown, but am finding it difficult to stop them from reaching the parent
body: <p>I'm working on a <a href="http://webhooks.org/" rel="nofollow noreferrer">Web Hook</a> in .NET 4.0 that will run a lambda asynchronously and then post the result to a given URI when it is finished.</p>
  
  <p>I've got that to work, but now I want the Task to handle any exceptions that are thrown, and am finding it difficult to stop them from reaching the parent.</p>
  
  <p>Here's part of my code:</p>
  
  <pre><code>private readonly Func&lt;T&gt; _startTask;
  private readonly string _responseUri;
  
  public Task&lt;T&gt; Begin()
  {
      var task = new Task&lt;T&gt;(_startTask);
      task.ContinueWith&lt;T&gt;(End);
      task.Start();
      return task;
  }
  
  private T End(Task&lt;T&gt; task)
  {
      if (task.IsFaulted)
      {
          return HandleException(task);
      }
  
      var result = task.Result;
      WebHookResponse.Respond(result, _responseUri);
      return result;
  }
  
  private T HandleException(Task&lt;T&gt; task)
  {
      WebHookResponse.HandleException(task.Exception.InnerException, _responseUri);
      return null;
  }
  </code></pre>
  
  <p>An alternative version that I have tried calls <code>ContinueWith()</code> twice to register one continuation to run <code>OnlyOnRanToCompletion</code> and one to run <code>OnlyOnFaulted</code>. (I'm not sure if calling <code>ContinueWith()</code> twice is correct.):</p>
  
  <pre><code>public Task&lt;T&gt; Begin()
  {
      var task = new Task&lt;T&gt;(_startTask);
      task.ContinueWith&lt;T&gt;(End, TaskContinuationOptions.OnlyOnRanToCompletion);
      task.ContinueWith&lt;T&gt;(HandleException, TaskContinuationOptions.OnlyOnFaulted);
      task.Start();
      return task;
  }
  
  private T End(Task&lt;T&gt; task)
  {
      var result = task.Result;
      WebHookResponse.Respond(result, _responseUri);
      return result;
  }
  
  private T HandleException(Task&lt;T&gt; task)
  {
      WebHookResponse.HandleException(task.Exception.InnerException, _responseUri);
      return null;
  }
  </code></pre>
  
  <p>So basically I want a way for each Task handle its own exceptions via a continuation function. As it stands the HandlException continuation function is never being called in either of the above examples.</p>
  
  <p>I am causing the exceptions in a test case, and I should mention that I am using a <code>Tasks.WaitAll(tasks);</code> call on an array of Tasks to make sure all of the tasks are complete before making my assertions, and I am not sure if that call makes a difference to how exceptions are handled by the Tasks. Currently WaitAll throws an AggregationException which aggregates the exceptions for each of the Tasks because they aren't being handled by the HandleException continuation function.</p>