TimothyP TimothyP - 2 months ago 25
C# Question

Catch an exception thrown by an async method

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()
{
var x = await DoSomethingAsync();
/* Handle the result, but sometimes an exception might be thrown
For example, DoSomethingAsync get's data from the network
and the data is invalid... a ProtocolException might be thrown */
}

public void DoFoo()
{
try
{
Foo();
}
catch (ProtocolException ex)
{
/* The exception will never be caught
Instead when in debug mode, VS2010 will warn and continue
when deployed the app will simply crash. */
}
}


So basically I want the exception from the async code to bubble up in to my calling code
if that is even possible at all.

Answer

It's somewhat weird to read but yes, the exception will bubble up to the calling code - but it will only do so if you await or Wait() the call to Foo

public async void DoFoo()
{
    try
    {
        await Foo();
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught because you've awaited the call. */
    }
}

//or//

public void DoFoo()
{
    try
    {
        Foo().Wait();
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught because you've awaited the call. */
    }
} 

Note that using Wait() may cause your application to block, if .Net decides to execute your method synchronously.

This explanation http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions is pretty good - it discusses the steps the compiler takes to achieve this magic.