Sub topic 7
Handling errors in asynchronous code
This chapter assumes you can write async functions and use await, and that you know how try, catch, and finally work in synchronous Dart. You should also know what a Future is and how then callbacks work. Here you will learn how a Future carries an error, how that error reaches your code, and what happens when nobody handles it.
How a Future fails
A Future<T> finishes in one of two ways: with a value of type T, or with an error. The error is an object plus an optional stack trace. It stays inside the Future until something listens for it.
An exception thrown inside an async function never escapes to the caller as a normal throw. The function returns a Future, and that Future completes with the error. The caller sees the error only when it consumes the Future. There are two ways to do that:
awaitthe Future, which rethrows the error at theawaitexpression.- Attach callbacks such as
then,catchError, orwhenComplete.
try, on, catch, and finally with await
Because await rethrows, you handle asynchronous errors with the same syntax you use for synchronous ones.
Future<int> parseAge(String input) async {
final age = int.tryParse(input);
if (age == null) {
throw FormatException('Not a number', input);
}
return age;
}
Future<void> main() async {
try {
print(await parseAge('42'));
print(await parseAge('abc'));
} on FormatException catch (e) {
print('Bad input: ${e.message}');
} finally {
print('done');
}
}The program prints 42, then Bad input: Not a number, then done. The finally block runs whether the Future succeeded or failed. It can contain await too, so it suits asynchronous cleanup such as closing a connection.
Some details about the clauses:
on FormatException catch (e)matches only that type (and its subtypes). Clauses are checked in order and the first match wins, so put specific types before general ones.catch (e)with nooncatches everything thrown, includingErrorsubclasses such asStateErrororTypeError. These usually signal bugs rather than conditions to recover from.on Exceptioncatches onlyExceptionsubtypes. This is a reasonable default when you want to recover from expected failures but let programming mistakes crash loudly.catch (e, st)gives you the stack trace as a second argument.
Future<void> main() async {
try {
await Future<void>.delayed(
const Duration(milliseconds: 50),
() => throw StateError('broken invariant'),
);
} on Exception catch (e) {
print('recoverable: $e'); // not reached: StateError is an Error
} catch (e, st) {
print('unexpected: $e');
print(st); // stack trace captured when the error was thrown
}
}StateError extends Error, not Exception, so the first clause is skipped and the general catch handles it.
Rethrowing and wrapping errors
Sometimes a layer should log an error and pass it on. Use rethrow, which keeps the original stack trace. Writing throw e instead starts a new trace at the throw line, and you lose the record of where the failure began.
When you want to convert the error into a different type, keep the original trace with Error.throwWithStackTrace:
class ConfigException implements Exception {
ConfigException(this.message);
final String message;
@override
String toString() => 'ConfigException: $message';
}
Future<String> readRaw() async => throw const FormatException('bad bytes');
Future<String> loadConfig() async {
try {
return await readRaw();
} on FormatException catch (e, st) {
Error.throwWithStackTrace(ConfigException('invalid file: ${e.message}'), st);
}
}
Future<void> main() async {
try {
await loadConfig();
} on ConfigException catch (e) {
print(e);
}
}Callback style: catchError and whenComplete
Before async and await, errors were handled on the Future itself. These methods are still common in library code and in short expressions.
| Method | Runs when | Typical use |
|---|---|---|
| `then(onValue)` | The Future completes with a value | Transform the result |
| `catchError(onError)` | The Future completes with an error | Recover or translate the error |
| `whenComplete(action)` | Either outcome | Cleanup, like `finally` |
Future<int> loadCount() {
return Future.delayed(
const Duration(milliseconds: 300),
() => throw StateError('no data'),
);
}
// Callback style
Future<String> describeWithThen() {
return loadCount()
.then((count) => 'Count is $count')
.catchError((Object e) => 'Failed: $e');
}
// Equivalent with async and await
Future<String> describeWithAwait() async {
try {
final count = await loadCount();
return 'Count is $count';
} catch (e) {
return 'Failed: $e';
}
}
Future<void> main() async {
print(await describeWithThen());
print(await describeWithAwait());
}Both functions print Failed: Bad state: no data. The second form reads top to bottom like synchronous code, which is why most Dart code prefers it.
catchError has a typing trap. Its handler must return a value compatible with the Future's type, or throw. If you call catchError on a Future<int> and the handler returns a String, the code compiles in some cases but fails at runtime with a type error. Keep the types aligned. The describeWithThen example is safe because then already turned the Future into a Future<String> before catchError ran.
catchError also catches errors raised by earlier then callbacks in the chain, not only the original Future's error. This is often what you want. It does mean one catchError at the end covers the whole chain.
Errors from parallel work
Future.wait takes several Futures and completes when all of them succeed. If any one fails, the combined Future completes with that error, and you handle it with ordinary try/catch.
Future<int> task(int n) async {
await Future<void>.delayed(Duration(milliseconds: 100 * n));
if (n == 2) throw ArgumentError('task $n failed');
return n;
}
Future<void> main() async {
try {
final results = await Future.wait([task(1), task(2), task(3)]);
print(results);
} on ArgumentError catch (e) {
print('wait failed: ${e.message}');
}
}Three behaviors matter here:
- The other Futures keep running.
Future.waitcannot cancel them. Their later errors are consumed bywait, so they do not crash the program, but you also cannot observe them. - By default, the combined Future waits for every input to finish before reporting the first error. Passing
eagerError: truereports it as soon as it occurs. - With
cleanUp, you can supply a function that disposes of successful results (for example, closing connections) when the overall call fails.
In Dart 3 you can also write await [f1, f2].wait on a list of Futures. When several fail, it throws a ParallelWaitError that holds every value and every error. This helps when you need to know about all failures rather than only the first.
If you want partial results, catch inside each task so that nothing throws out of it:
Future<int?> safeTask(int n) async {
try {
return await task(n);
} on ArgumentError {
return null;
}
}
Future<void> main() async {
final results = await Future.wait([safeTask(1), safeTask(2), safeTask(3)]);
print(results); // [1, null, 3]
}return await inside try
A plain return of a Future from an async function passes the Future out without waiting for it. A failure then happens after the function has left the try block, so the catch never sees it.
Future<String> fetchData() async {
throw Exception('network down');
}
Future<String> loadWithFallback() async {
try {
return await fetchData();
} catch (e) {
return 'fallback';
}
}
Future<void> main() async {
print(await loadWithFallback());
}This prints fallback. If you change return await fetchData() to return fetchData(), the exception escapes to the caller of loadWithFallback, and the catch is skipped. Outside a try block, return await adds nothing, and the Dart linter flags it. Inside one, it is required.
Unhandled errors
If a Future completes with an error and nothing is listening, the error is reported to the current zone's uncaught-error handler. In a plain dart run program this prints the exception and stack trace and ends the program. Two situations cause this:
- A Future that was never awaited. Calling
failingTask();withoutawaitorunawaiteddiscards the Future, and its error with it. - A listener attached too late. The error is reported when the Future completes, so a listener must be in place before the current event finishes.
Future<void> failingTask() async => throw StateError('lost');
Future<void> main() async {
final pending = failingTask(); // starts now, fails almost immediately
await Future<void>.delayed(const Duration(milliseconds: 100));
try {
await pending; // too late: the error was already reported as unhandled
} catch (e) {
print('caught: $e');
}
}Run this and the program terminates with an unhandled StateError before the try is reached. The fix is to start the work and await it in the same flow, or to attach the handler right away with pending.catchError(...). When you deliberately start work and do not care about the result, wrap it in unawaited(...) from dart:async and handle errors inside the task itself.
As a last line of defense, runZonedGuarded installs a handler for every uncaught error raised within its zone:
import 'dart:async';
Future<void> failingTask() async => throw StateError('lost');
void main() {
runZonedGuarded(() {
failingTask(); // nobody awaits it
}, (error, stack) {
print('last resort: $error');
});
}Use this for logging and crash reporting, not for normal control flow. In a Flutter app the equivalent hooks are FlutterError.onError for framework errors and PlatformDispatcher.instance.onError for asynchronous ones.
Summary of rules
- Await Futures inside
tryto catch their errors. Usereturn awaitthere. - Catch specific types with
on. CatchErrorsubclasses only at the outermost layer. - Use
rethroworError.throwWithStackTraceto keep stack traces. - Put cleanup in
finallyorwhenComplete. - Never discard a Future that can fail.
Exercise
In the function below, why does the catch block never run, and what single change makes it run? Future<String> fetchData() async => throw Exception('down'); Future<String> load() async { try { return fetchData(); } catch (e) { return 'fallback'; } }
Show answer
return fetchData(); returns the failing Future to the caller without awaiting it inside the try block, so the error surfaces after the function has left the try and the catch is skipped. Changing it to return await fetchData(); makes the error rethrow inside the try, so the catch returns 'fallback'.
Exercise
You call Future.wait([a(), b(), c()]) and b() fails after 100 ms while c() is still running and will fail at 500 ms. What does the caller see, and what happens to c()'s error?
Show answer
The caller's await throws b()'s error (by default after all three Futures have finished, or immediately with eagerError: true). c() is not cancelled and keeps running. Its later error is consumed by Future.wait, so it does not crash the program, and the caller never sees it. To observe every failure, catch inside each task or use the Dart 3 .wait extension, which throws a ParallelWaitError containing all errors.
Exercise
Rewrite this chain using async, await, and try/catch/finally: loadCount().then((c) => 'Count $c').catchError((e) => 'Failed').whenComplete(() => print('cleanup')).
Show answer
Future<String> describe() async { try { final c = await loadCount(); return 'Count $c'; } catch (e) { return 'Failed'; } finally { print('cleanup'); } }