Reputation: 493
I'm trying to implement exception handling from a task but I just can't seem to get it right. I've found a few examples of the pattern but no matter what I try I always seem to get unhandled exceptions from within the task itself. I must be missing something, but I can't see what. Any help would be very much appreciated.
I've tried an example I found on MSDN but that doesn't work for me:
https://msdn.microsoft.com/en-us/library/dd997415(v=vs.110).aspx
And I followed the answer to this question but when I run the fix in Visual Studio it still complains about unhandled exceptions:
This is the code that I initially wrote:
static void Main(string[] args)
{
TestAsync().ContinueWith(t =>
{
Console.WriteLine(t.Exception.ToString());
}, TaskContinuationOptions.OnlyOnFaulted);
Console.ReadKey();
}
static async Task<IEnumerable<string>> TestAsync()
{
IEnumerable<string> list = null;
try
{
list = await TestTask();
}
catch (Exception)
{
Console.WriteLine("Caught!");
}
return list;
}
static Task<IEnumerable<string>> TestTask()
{
var task = new Task<IEnumerable<string>>(() =>
{
throw new AggregateException("This is a test");
});
task.Start();
return task;
}
Upvotes: 3
Views: 1820
Reputation: 127543
Just hit continue after VS breaks, you will see it gets to your ContinueWith. It is just a quirk of the debugger because it cannot find a try/catch within your code that handles the execption.
If you don't want the debugger to stop and show you a message you will need to disable "Just My Code" in the debugger options so that the try/catch that lives inside of Task
gets counted as the thing that catches the exception.
Upvotes: 5