2
votes

I'm trying to deal with exceptions inside of tasks, so far I've looked at the following links:

https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library

How to handle Task.Run Exception

If I am correct, they suggest that the following code would not cause a User-Unhandled Exception.

    public async void TestMethod()
    {
        try
        {
            await Task.Run(() => { throw new Exception("Test Exception"); });
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

However, I am getting a User-Unhandled Exception. I want to handle the exception outside of the Task so I can avoid writing code for changing the UI from a different thread. What am I doing wrong?

Here is a printscreen of the exception:

enter image description here

1
Why are you catching AggregateException? AggregateException is thrown by Task.Wait() and Task.Result, but you're awaiting your Task. You can just catch the exception directly -- catch (Exception ex) { Console.WriteLine(ex.Message); } - canton7
@canton7 Hey, yes I was orignally just catching the one exception as you're saying. That was just me trying different things from one of the links I posted in the question - David Andrew Thorpe
The first link talks about Task in the context of the pre-async/await world: you can see that all of their examples use Task.Wait() / Task.Result. Your second link has answers which do try { await ... } catch (Exception e) { ... } - canton7
What problems? I just tested the new code and it works exactly as expected (it writes "Test Exception" to the console) - Gabriel Luci
That looks like Visual Studio is configured to break on all exceptions, even handled ones. Just hit F5 and it will probably continue execution into the catch block. - Gabriel Luci

1 Answers

3
votes

To answer your original question, before you edited it, one of the features of await is that it will "unwrap" not only the return value, but any exceptions too. So if you need to catch an exception, it will not be an AggregateException like it would be if you used .Wait() or .Result.

That's a Good Thing™

Also, it looks like Visual Studio is configured to break on all exceptions, even handled ones. This is handy (I always keep VS set like that because sometimes weird things can happen when exceptions are caught and hidden), but you just have to be aware of it. You can press F5 or F10 to continue execution and it should continue into the catch block.