madaboutcode
madaboutcode

Reputation: 2137

Xamarin: Exceptions raised from tasks are not propagated

I have the following code in Xamarin (tested in ios):

private static async Task<string> TaskWithException()
{
    return await Task.Factory.StartNew (() => {
        throw new Exception ("Booo!");
        return "";
    });
}

public static async Task<string> RunTask()
{
    try
    {
        return await TaskWithException ();
    }
    catch(Exception ex)
    {
        Console.WriteLine (ex.ToString());
        throw;
    }
}

Invoking this as await RunTask(), does throw the exception from the TaskWithException method, but the catch method in RunTask is never hit. Why is that? I would expect the catch to work just like in Microsoft's implementation of async/await. Am I missing something?

Upvotes: 13

Views: 2894

Answers (1)

jzeferino
jzeferino

Reputation: 7850

You cant await a method inside of a constructor, so thats why you can't catch the Exception.

To catch the Exception you must await the operation.

I have here two ways of calling an async method from the constructor:

1. ContinueWith solution

RunTask().ContinueWith((result) =>
{
    if (result.IsFaulted)
    {
        var exp = result.Exception;
    }      
});

2. Xamarin Forms

Device.BeginInvokeOnMainThread(async () =>
{
    try
    {
        await RunTask();    
    }
    catch (Exception ex)
    {
        Console.WriteLine (ex.ToString());
    }    
});

3. iOS

InvokeOnMainThread(async () =>
{
    try
    {
        await RunTask();    
    }
    catch (Exception ex)
    {
        Console.WriteLine (ex.ToString());
    }    
});

Upvotes: 7

Related Questions