Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
{

}
like image 779
Bryan Stump Avatar asked Mar 21 '26 08:03

Bryan Stump


1 Answers

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

like image 175
Bryan Stump Avatar answered Mar 23 '26 03:03

Bryan Stump



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!