CodeBlanks Logo Icon CodeBlanks

Future.error

Learn Future.error and catchError.

Future.error

A Future can also complete with an error. Future.error(Exception("error")) creates a Future that completes immediately with an error. .then only runs on success; to catch the error you use .catchError.

Example: Future.error(Exception("oops")).then((v) => print(v)).catchError((e) => print(e));. Here .then is skipped, .catchError runs and prints the error. This is the asynchronous version of try/catch. The return of .catchError is a Future; so the rest of the chain is still a Future. To check multiple error types you can also pass a test function.

catchError details

.catchError takes a callback. This callback receives the error as a parameter. .catchError((e) => print("error: \$e")). Since the return is a Future, the rest of the chain is still a Future; so you can recover and continue after an error.

To catch a specific error type you can pass a test parameter: .catchError((e) => print(e), test: (e) => e is FormatException). This catches only FormatException errors; others propagate up the chain. This is the asynchronous counterpart of the on clause. To run cleanup code on error there is also .whenComplete; the asynchronous counterpart of finally.

Practice Your turn: catch the error

Create a Future that fails with Future.error(Exception("oops")). Write the success path with .then((v) => print(v)) and print the error with .catchError((e) => print(e)). The error reaches the screen.

Starter code

main.dart
void main() {
  // Create a Future with Future.error
  // .then for success
  // .catchError prints the error
}

Sample solution

main.dart
void main() {
  Future.error(Exception("oops")).then((v) => print(v)).catchError((e) => print(e));
}

Expected output

Exception: oops

Questions and answers

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

1 When does .then run?

main.dart
Future.error(Exception("error"))
  .then((v) => print(v))
  .catchError((e) => print(e));
  • Only on error
  • Only on success Correct answer
  • Never
  • Always

Explanation: then runs only on success.

2 catchError

Question
Future.error(Exception("oops")).then((v) => print(v)).____((e) => print(e));
Answer
Future.error(Exception("oops")).then((v) => print(v)).catchError((e) => print(e));

Explanation: catchError catches the error.

3 Match Future.error

Term Meaning
Future.error completes with an error
.then runs on success
.catchError catches the error
.whenComplete always runs

All lessons in Beginner