user441365
user441365

Reputation: 4024

catching specific exceptions coming from another Task method

I have these 2 methods, and I know for sure that DoSomethingAsync returns a FormatException. However it is always catched in the last catch “Exception”

Why does CallSomethingAsync never catch the FormatException?

       public Task DoSomethingAsync()
       {
            //Do something that throws a FormatException 

            return Task.FromResult(0);           
       }

   public virtual string CallSomethingAsync()
   {
        try
        {
            this.DoSomethingAsync().Wait();

            return “Ok”;
        }
        catch (FormatException)
        {
            return “FormatException”;
        }
        catch (Exception)
        {
            return “GeneralException”;
        }
   }

Upvotes: 0

Views: 36

Answers (1)

Duncan Howe
Duncan Howe

Reputation: 3025

Because the Task may return one or more Exceptions it throws an AggregateException containing all of the exceptions that occurred during the Task's execution.

You need to enumerate the InnerExceptions collection to explicitly handle the different types of Exception.

Upvotes: 2

Related Questions