locked
Task Exception handling

    Question

  • Hi

    I've been struggling with this problems for a while,,, and need some help to sort things out.

    Using VS 2013 units tests,, I have the following simplified unit test.

            [TestMethod]
            public async WTF()
            { 
                Task task;
    
                try
                {
                    task = Task.Run(
                                    () =>
                                    {
                                        throw new Exception("Try to catch me");                                   
                                    });
                    await task;
                }
                catch (AggregateException ex_agg)
                {
                }
                catch (Exception ex_ex)
                {
                }
            }

    I har expected that the line 

    throw new Exception("Try to catch me");	

    would cause a AggregateException to be thrown,, and I could  manage cause of the exception inside the corresponding catch clause.

    Instead a Exception catch is always "activated". "ex_ex" contains no inner exception,, 

    Changing "Enable just my code" makes no difference for the result.

    What am I doing wrong???

    //regards
    //lg


    lg

    Saturday, February 22, 2014 6:23 PM

Answers

  • no the await statement gets the exception out of the aggregated exception for you. chante the await task to

    task.Wait();
     and you get the aggregatedexception again. Ofcourse you dont want to do. so just handle the exception instead of the aggregated exception

    Microsoft Certified Solutions Developer - Windows Store Apps Using C#

    Saturday, February 22, 2014 7:07 PM