Noisy88
Noisy88

Reputation: 183

Is this correct way to handle an exception?

I've argued with my colleague about handling exceptions in Task.Run blocks.

For example, I have this code:

private static async Task MainAsync()
{
    try
    {
        await Task.Run(() => throw new Exception());
    }
    catch (Exception)
    {
        Console.WriteLine("oops");
    }
}

If I run this code (in debug mode), I'll get the message from vs2019 about the unhandled exception. But if I press the continue button, the app will work correctly and the exception will be handled.

Is it the correct way to catch exceptions from Task.Run?

Upvotes: 0

Views: 113

Answers (1)

Michał Turczyn
Michał Turczyn

Reputation: 37460

Generally, exception in tasks (objects of class Task) are placed on tasks, i.e. if some code in a task throws exception inside that task - it is stored in Exception property in Task class.

await operator automatically "unpacks" exception and throws. So your way is totally correct, but I think stack trace might change - so you need to keep that in mind.

Upvotes: 2

Related Questions