Search code examples
c#.netwindows-runtimewindows-store-appswinrt-async

Custom Exception thrown as Aggregate Exception


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
{

}

Solution

  • 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