Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - What happens to a Task that throws an exception but the caller method is already done?

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?

like image 722
shay__ Avatar asked Sep 12 '25 23:09

shay__


2 Answers

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.

like image 186
Luaan Avatar answered Sep 15 '25 12:09

Luaan


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).

like image 35
Servy Avatar answered Sep 15 '25 13:09

Servy