Using the async CTP from Microsoft for .NET, is it possible to catch an exception thrown by an async method in the calling method?
public async void Foo()
{
The reason the exception is not caught is because the Foo() method has a void return type and so when await is called, it simply returns. As DoFoo() is not awaiting the completion of Foo, the exception handler cannot be used.
This opens up a simpler solution if you can change the method signatures - alter Foo()
so that it returns type Task
and then DoFoo()
can await Foo()
, as in this code:
public async Task Foo() {
var x = await DoSomethingThatThrows();
}
public async void DoFoo() {
try {
await Foo();
} catch (ProtocolException ex) {
// This will catch exceptions from DoSomethingThatThrows
}
}