Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/await throwing unhandled exception

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:

ContinueWith TaskContinuationOptions.OnlyOnFaulted does not seem to catch an exception thrown from a started task

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;
}
like image 506
Simon Stanford Avatar asked Jun 13 '26 06:06

Simon Stanford


1 Answers

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.

like image 139
Scott Chamberlain Avatar answered Jun 15 '26 18:06

Scott Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!