Handling Async Errors

Catching exceptions in asynchronous code

Posted by Rodrigo Castro on December 24, 2024

Async methods can throw exceptions, just like normal ones. Handle them with try/catch!

🛑 Catching Exceptions in Async Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
async Task FailAsync()
{
    await Task.Delay(500);
    throw new Exception("Something went wrong!");
}

async Task MainAsync()
{
    try
    {
        await FailAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Caught: {ex.Message}");
    }
}

⚠️ Why Use try/catch with await?

  • The exception is thrown where you await the method.
  • If you don’t catch it, your app may crash.

💡 Try It!

Write an async method that throws an exception, and handle it with try/catch.

1
2
3
4
async Task ThrowErrorAsync()
{
    throw new InvalidOperationException("Oops!");
}

Next: Async best practices!