Back to results for “Asynchronous Programming”
Flutter › Dart Asynchronous Programming (Future & async/await)

How do you properly handle errors that occur during an asynchronous operation using a try catch block combined with async and await?

Intermediate

Answer

Wrapping an await expression within a standard try catch block lets you handle any error that might occur during that specific asynchronous operation using exactly the same familiar error handling syntax used for regular synchronous code, meaning if the awaited Future actually completes with an error rather than a successful value, that error is thrown at the exact point of the await expression and can be caught by a surrounding catch block, letting you respond appropriately, such as displaying a friendly error message to the user, rather than allowing an unhandled exception to potentially crash the entire application.
Future<void> loadData() async {
  try {
    final data = await fetchDataFromServer();
    displayData(data);
  } catch (error) {
    showErrorMessage('Failed to load data: $error');
  }
}
Real-world example A news app wraps its network fetching call in a try catch block, gracefully displaying a friendly retry message to the user if the network request fails, rather than allowing an unhandled exception to crash the entire application.

Common follow-ups: What is the difference between catching a generic Exception versus a more specific error type?;How does error handling for a Future differ from error handling for a Stream?