I thought that async methods were supposed to behave like normal methods until they arrived at an await.
Why does this not throw an exception?
Is there a way to have the exception thrown without awaiting?
using System;
using System.Threading.Tasks;
public class Test
{
public static void Main()
{
var t = new Test();
t.Helper();
}
public async Task Helper()
{
throw new Exception();
}
}
An exception thrown inside an
async
method is, by design, stored inside the returned task. To get your hands on the exception you can:await
the task:await t.Helper();
Wait
the task:t.Helper().Wait();
Exception
property after the task has been completed:var task = t.Helper(); Log(task.Exception);
t.Helper().ContinueWith(t => Log(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
Your best option is the first one. Simply
await
the task and handle the exception (unless there's a specific reason you can't do that). More in Task Exception Handling in .NET 4.5