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?
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());
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With