13

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?

i3arnon
  • 113,022
  • 33
  • 324
  • 344
madaboutcode
  • 2,137
  • 1
  • 16
  • 23

1 Answers1

7

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());
    }    
});
jzeferino
  • 7,700
  • 1
  • 39
  • 59
  • 2
    Thank you for taking the time to respond to this old question. From what I remember, we used #2 to resolve the problem at that time. Shame on me for not following through and answering my own question! :( – madaboutcode Jul 02 '16 at 10:42