3

When throwing a custom exception from a Task.Run(...).Result, the catch block finds an AggregateException instead of the CustomException. Why?

   public MainPage()
    {
        this.InitializeComponent();
        CallAMethod();
    }

    static bool AMethod()
    {
        return Task.Run(() =>
        {
            throw new CustomException();
            return false;
        }).Result;
    }

    static bool CallAMethod()
    {
        try
        {
            return AMethod();

        }
        catch (CustomException e)
        {
            //not caught
            throw;
        }
        catch (Exception ex)
        {
            //caught?
            throw;
        }
    }

Here is the custom Exception class

class CustomException : Exception
{

}
Bryan Stump
  • 1,419
  • 2
  • 17
  • 26
  • 4
    http://blogs.msdn.com/b/pfxteam/archive/2011/09/28/task-exception-handling-in-net-4-5.aspx ... "When you use Task.Wait() or Task.Result on a task that faults, the exception that caused the Task to fault is propagated, but it’s not thrown directly… rather, it’s wrapped in an AggregateException object, which is then thrown." ... you can access the CustomException inside it ... http://stackoverflow.com/questions/22872995/flattening-of-aggregateexceptions-for-processing – Colin Smith Aug 10 '14 at 00:05
  • i believe you could add this as an answer, since op framed the question as "why?" – glopes Aug 10 '14 at 03:14
  • @colinsmith thanks for the answer. I did not know about Exception.Flatten and will use this method. Answer posted. 2 days before I can mark as answer. – Bryan Stump Aug 10 '14 at 03:46

1 Answers1

9

from @colinsmith

"When you use Task.Wait() or Task.Result on a task that faults, the exception that caused the Task to fault is propagated, but it’s not thrown directly… rather, it’s wrapped in an AggregateException object, which is then thrown." ... you can access the CustomException inside it

See: Flattening of AggregateExceptions for Processing

crthompson
  • 15,653
  • 6
  • 58
  • 80
Bryan Stump
  • 1,419
  • 2
  • 17
  • 26