3

What will happen (and why) if the following if statement is satisfied, and Bar() throws an exception?

    async Task Foo()
    {
        Task<object> myTask = Bar();
        if (condition)
        {
            return;
        }
        else
        {
            await myTask;
            // ....
            return;
        }
    }

Will the exception be caught? By who?

shay__
  • 3,815
  • 17
  • 34
  • @Luaan Whoops, yes of course. :) –  Aug 06 '15 at 15:45
  • possible duplicate of [A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was](http://stackoverflow.com/questions/7883052/a-tasks-exceptions-were-not-observed-either-by-waiting-on-the-task-or-accessi) – sstan Aug 06 '15 at 15:54

2 Answers2

5

No, the exception won't be caught. You need to specifically add a continuation to the Task (note that when you await a task you're adding a continuation to it).

Servy
  • 202,030
  • 26
  • 332
  • 449
4

If Bar throws an exception, it will be thrown right at the point where you call it.

However, if the Task that Bar returns wraps an exception, what happens depends on your version of .NET runtime - for .NET 4.0, it will bring down your entire process, because it eventually causes the exception to be thrown on a finalizer thread (or a thread-pool thread). For .NET 4.5+, the exception will be silently disposed of.

In any case, you don't want either. You should always explicitly handle any asynchronous exceptions that can be propagated in the asynchronous task. If you don't want to await the task in some branch of your code (say, you're pre-loading data you think you'll need, but don't), at least bind a continuation on the task to handle any possible exceptions gracefully.

Luaan
  • 62,244
  • 7
  • 97
  • 116
  • I think you meant that for .NET 4.0 the exception bring down the entire process, and starting with .NET 4.5+, this has changed. Reference: http://blogs.msdn.com/b/pfxteam/archive/2011/09/28/10217876.aspx – sstan Aug 06 '15 at 15:53