1

After executing this code:

try
{
    DoSomething();
}
catch (TaskCanceledException e)
{
    DealWithCancelledTaskException(e);
    throw;
}
catch (Exception e)
{
    DealWithNormalException(e);
    throw;
}

The exception is raised. DoSomething is supposed to throw TaskCancelledException, but it throws System.AggregateException containing one exception of type TaskCancelledException and is caught as normal Exception.

How can I catch this exception as TaskCancelledException?

Jaroslaw Matlak
  • 574
  • 1
  • 12
  • 23
  • Possible duplicate of [list of exceptions](https://stackoverflow.com/questions/11376829/list-of-exceptions) – Alex Feb 19 '18 at 09:14
  • 2
    you would get `Aggregate` exception , hence it is caught has normal exception – Jaya Feb 19 '18 at 09:14
  • Task-related exceptions are always raised as AggregateException, where the InnerException member is the actual exception you are interested in. – Nick Feb 19 '18 at 09:15
  • It's probably `AggregateException` like @Jaya wrote, but it's impossible to guess what `DoSomething` does. Provide a [mcve]. – vgru Feb 19 '18 at 09:15
  • It's `System.AggregateException` – Jaroslaw Matlak Feb 19 '18 at 09:20
  • The question is why are you mixing synchronous and asynchronous code? The golden rule is "async all the way". This way you wouldn't get an AggregateException, because "await" unwraps these. – ckuri Feb 19 '18 at 10:35

1 Answers1

4

It is most likely that your code is throwing an AggregateException

Firstly try explicitly catching AggregateException. Then to access the exception that has been wrapped up by the aggregate exception use the InnerException Property. You can also access the list of all exceptions that have been aggregated (if there is or could be more than 1) by accessing the InnerExceptions property which gives you a list of the exceptions that this exception has aggregated

Dave
  • 2,829
  • 3
  • 17
  • 44