I am trying to get more familiar with async/await programming and exception handling.
static void Main(string[] args)
{
TestAsyncException();
}
private static async void TestAsyncException()
{
try
{
var result = await Task.Factory.StartNew(() => DoSomething());
//do something with the result
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private static int DoSomething()
{
throw new Exception("Exception was thrown!");
}
I am expecting the Exception
to be handled gracefully but instead the code execution stops and I get
An exception of type 'System.Exception' occurred in .. but was not handled in user code.
But then when I continue executing the code the Exception
actually gets caught (and the message is displayed to the Console
).
How am I supposed to catch the Exception
without breaking the execution of my code?