CodeBlanks Logo Icon CodeBlanks

Async errors

Learn async errors and try/catch.

Async errors

Errors in asynchronous functions return inside a Future. They are caught with try/await/catch.

When a Future returns an error, the await call throws: try { await fetchUser(); } catch (e) { print(e); }.

main must now be async: void main() async { ... }. This is required to use await.

An async error example

An async function can throw: Future<void> fetchUser() async { throw Exception('offline'); }.

The caller: try { await fetchUser(); } catch (e) { print(e); }. await waits for the Future; if there is an error it falls into catch.

This looks the same as synchronous try/catch; the only difference is the await keyword.

Practice Async error handling

Define Future<void> fetchUser() async { throw Exception('offline'); }. Make main async: call it with try { await fetchUser(); } catch (e) { print(e); }.

Starter code

main.dart
// Define the fetchUser function

void main() async {
  // call fetchUser with await, catch the error
}

Sample solution

main.dart
Future<void> fetchUser() async {
  throw Exception('offline');
}

void main() async {
  try {
    await fetchUser();
  } catch (e) {
    print(e);
  }
}

Expected output

Exception: offline

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Catch with await

Question
try { await fetch(); } ____ (e) { print(e); }
Answer
try { await fetch(); } catch (e) { print(e); }

Explanation: catch (e) catches the error.

2 Async error concepts

Term Meaning
await Waits the Future
catch Catches the error
Future Async value
async Async function

3 How is an error caught in an async function?

  • on Error catch
  • if (error)
  • try { await ... } catch Correct answer
  • switch (error)

Explanation: the await call goes inside try, catch handles it.

All lessons in Intermediate