Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 488
madaboutcode Avatar asked Sep 08 '14 17:09

madaboutcode


1 Answers

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());
    }    
});
like image 198
jzeferino Avatar answered Sep 24 '22 22:09

jzeferino