Search code examples
c#async-ctp

Not catching exception thrown by TaskEx.Run's task


I'm having trouble with the async CTP, trying to figure out what the correct way to handle exceptions is. The code below crashes my program, when as far as I can tell, the await should be catching and rethrowing the exception in the context it is called from, so the Not caught! block should catch the exception.

try {
  await TaskEx.Run(() => {
    throw new Exception();
  });
} catch {
  // Not caught!
}

Thanks for any help or suggestions.


Solution

  • Works fine for me using the beta (rather than the CTP, hence the TaskEx becoming Task):

    using System;
    using System.Threading.Tasks;
    
    class Test
    {
        static void Main()
        {
            Task t = Foo();
            t.Wait();
        }
    
        static async Task Foo()
        {
            try
            {
                await Task.Run(() => { throw new Exception(); });
            }
            catch (Exception e)
            {
                Console.WriteLine("Bang! " + e);
            }
        }
    

    Output:

    Bang! System.Exception: Exception of type 'System.Exception' was thrown.
       at Test.<Foo>b__0()
       at System.Threading.Tasks.Task`1.InnerInvoke()
       at System.Threading.Tasks.Task.Execute()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter
                .HandleNonSuccessAndDebuggerNotification(Task task)
       at Test.<Foo>d__2.MoveNext()
    

    What does the same code do on your machine?