async try/catch
Learn to catch exceptions in async methods with try/catch.
async try/catch
Using try/catch inside an async method is the same as in synchronous code. You wrap the await call in a try block; if an error occurs, the catch block runs. Example: try { await DoWork(); } catch (Exception ex) { ... }.
Important: to catch the error you must use await. If you call DoWork() without awaiting, the error stored in the returned Task is silently ignored and surfaces elsewhere.
Catching exceptions
When an async method throws, the error is stored in the returned Task. When you await it, if the Task faulted, await rethrows the error; that is how the catch block catches it. So the async error flow starts with the await.
You can write multiple catches by error type: catch (InvalidOperationException ex) or a general catch (Exception ex). The most specific type must come first; otherwise the general catch swallows everything.
Exercise Catch the error with async try/catch
Define static async Task FailAsync(). In its body write await Task.CompletedTask; and throw new InvalidOperationException("Error");. Make Main a static async Task Main. Catch the error with try { await FailAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); } and print the message.
Show example solution
In FailAsync body write await Task.CompletedTask; and throw new InvalidOperationException("Error");. Make Main static async Task Main() and write try { await FailAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); }
Example solution:
using System;
using System.Threading.Tasks;
class Program
{
static async Task FailAsync()
{
await Task.CompletedTask;
throw new InvalidOperationException("Error");
}
static async Task Main()
{
try
{
await FailAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Test yourself
-
How do you set up async try/catch?
- Only in Main
- By wrapping the await call in a try block
- Before the async keyword
- After the Task.Run call
Show answer
By wrapping the await call in a try block — Correct. Wrapping the await call in a try block catches the error.
-
Complete the try block
static async Task Run() { ____ { await DoWork(); } catch (Exception ex) { Log(ex); } }Show answer
static async Task Run() { try { await DoWork(); } catch (Exception ex) { Log(ex); } } -
What happens to the error if you call without await?
- The error is thrown at once
- No error occurs
- The error sits in the Task; may explode elsewhere
- The error is caught automatically
Show answer
The error sits in the Task; may explode elsewhere — Correct. Without await, the error sits in the Task; it may be ignored or explode later.