Not catching exception thrown by TaskEx.Run's task

1.6k Views Asked by At

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.

3

There are 3 best solutions below

3
On BEST ANSWER

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?

0
On

A little bit of rearranging should work:

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

EDIT:

I get the same results as Jon Skeet due to the fact that I'm also running the VS11 beta. I cannot speak for the CTP.

0
On

Pro Tip: Visual Studio is telling you that the exception is unhandled, but if you F5 through, you will see that it does get caught.

(This from comments on Jon's answer, but I think it deserves its own answer)