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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With