Question

Running the following C# console app

class Program
{  static void Main(string[] args)
   {  Tst();
      Console.ReadLine();
   }
   async static Task  Tst()
   {
       try
       {
           await Task.Factory.StartNew
             (() =>
                {
                   Task.Factory.StartNew
                       (() =>
                         { throw new NullReferenceException(); }
                         , TaskCreationOptions.AttachedToParent
                        );
               Task.Factory.StartNew
                       (  () =>
                               { throw new ArgumentException(); }
                               ,TaskCreationOptions.AttachedToParent
                       );
                }
             );
    }
    catch (AggregateException ex)
    {
        // this catch will never be target
        Console.WriteLine("** {0} **", ex.GetType().Name);

//******  Update1 - Start of Added code
        foreach (var exc in ex.Flatten().InnerExceptions)
        {
             Console.WriteLine(exc.GetType().Name);
        }
//******  Update1 - End of Added code
    }
    catch (Exception ex)
    {
       Console.WriteLine("## {0} ##", ex.GetType().Name);
    }
 }

produces the output:

** AggregateException **

Though, the code above is reproducing the first snippet from "Async - Handling multiple Exceptions" blog article, which tells about it :

the following code will catch a single NullReferenceException or ArgumentException exception (the AggregateException will be ignored)

Where is the problem:

  1. the article is wrong?
    Which code/statements and how to change in order to correctly understand it?
  2. I made an error in reproducing the first code snippet of the article?
  3. It is due to a bug in .NET 4.0/VS2010 Async CTP extension, I am using?

Update1 (in response to svick's answer)

Upon adding the code

//******  Update1 - Start of Added code
        foreach (var exc in ex.Flatten().InnerExceptions)
        {
             Console.WriteLine(exc.GetType().Name);
        }
//******  Update1 - End of Added code

the produced output is:

** AggregateException **
NullReferenceException

So, as also commented Matt Smith:

the AggregateException that is caught, contains only one of the exceptions that was thrown (either the NullReferenceException or the ArgumentException depending on the order of execution of the child Tasks)

Most probably, the article is still correct or, at least, very useful. I just need to understand how to better read/understand/use it

Update2 (in response to svick's answer)

Executing svick's code:

internal class Program
{
  private static void Main(string[] args)
  {
    Tst();
    Console.ReadLine();
  }

  private static async Task Tst()
  {
    try
    {
      await TaskEx.WhenAll
        (
          Task.Factory.StartNew
            (() =>
               { throw new NullReferenceException(); }
            //, TaskCreationOptions.AttachedToParent
            ),
          Task.Factory.StartNew
            (() =>
               { throw new ArgumentException(); }
            //,TaskCreationOptions.AttachedToParent
            )

        );
    }
    catch (AggregateException ex)
    {
      // this catch will never be target
      Console.WriteLine("** {0} **", ex.GetType().Name);

      //******  Update1 - Start of Added code
      foreach (var exc in ex.Flatten().InnerExceptions)
      {
        Console.WriteLine("==="+exc.GetType().Name);
      }
      //******  Update1 - End of Added code
    }
    catch (Exception ex)
    {
      Console.WriteLine("## {0} ##", ex.GetType().Name);
    }
  }
}

produces:

## NullReferenceException ##

output.

Why isn't AggregateException produced or caught?

Was it helpful?

Solution

The article is wrong. When you run your code, the awaited Task contains an exception that looks something like this:

AggregateException
  AggregateException
    NullReferenceException
  AggregateException
    ArgumentException

What await (or, more specifically, TaskAwaiter.GetResult()) does here is that it takes the outer AggregateException and rethrows its first child exception. Here, that's another AggregateException, so that's what is thrown.

Example of code where a Task has multiple exceptions and one of them is directly rethrown after await would be to use Task.WhenAll() instead of AttachedToParent:

try
{
    await Task.WhenAll(
        Task.Factory.StartNew(() => { throw new NullReferenceException(); }),
        Task.Factory.StartNew(() => { throw new ArgumentException(); }));
}
catch (AggregateException ex)
{
    // this catch will never be target
    Console.WriteLine("** {0} **", ex.GetType().Name);
}
catch (Exception ex)
{
    Console.WriteLine("## {0} ##", ex.GetType().Name);
}

OTHER TIPS

In response to your "Update 2", the reasoning is still the same as in svick's answer. The task contains an AggregateException, but awaiting it throws the first InnerException.

The additional information you need is in the Task.WhenAll documentation (emphasis mine):

If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.

So that Task's exceptions will look like:

AggregateException 
    NullReferenceException 
    ArgumentException
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top