Sub topic 7
Handling errors in asynchronous code
This chapter assumes basic Dart syntax, functions, generics, callbacks, and running programs with dart run. It also assumes you understand that a Future<T> represents a result that completes later.
Where asynchronous errors go
A synchronous error is thrown while the current function is running. An asynchronous error completes a Future with an error. The error becomes visible when code awaits that Future or attaches an error handler.
A try block catches an asynchronous error only when the await happens inside the block. Creating a Future inside try is not enough.
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());
}fetchData throws after its asynchronous function starts. Because loadWithFallback uses await inside try, the catch clause receives the error and returns a fallback value.
An async function that throws does not throw directly to its caller. It returns a Future that completes with an error. Awaiting that Future rethrows the error at the await expression.
Use try, on, catch, and finally
Use on when you want to handle one particular exception type. Use catch when you need the error value, stack trace, or a broader fallback. Use finally for cleanup that must happen whether the operation succeeds or fails.
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, stackTrace) {
print('Bad input: ${e.message}');
print(stackTrace);
} catch (e) {
print('Unexpected error: $e');
} finally {
print('done');
}
}The second call completes with a FormatException. The on FormatException clause handles it, and finally still runs.
| Tool | Use it for |
|---|---|
| `try` and `catch` | Handling errors at an `await` point |
| `on SomeException` | Matching a specific exception type |
| `finally` | Closing resources or resetting state |
| `catchError` | Handling errors in a Future chain |
Handle errors with Future methods
Callback-style code can use catchError and whenComplete. The error handler must return a value compatible with the Future's type.
Future<int> loadCount() {
return Future.delayed(
const Duration(milliseconds: 300),
() => 7,
);
}
Future<String> describeCount() {
return loadCount()
.then((count) => 'Count is $count')
.catchError((Object error) => 'Failed: $error')
.whenComplete(() => print('load finished'));
}
Future<void> main() async {
print(await describeCount());
}For new code, async and await are often easier to read because the error path resembles synchronous code. Use Future methods when composing a chain or when a callback-based API already has that shape.
Avoid errors that escape your handler
This pattern does not catch the failure from fetchData:
Future<String> wrong() async {
try {
return fetchData();
} catch (e) {
return 'fallback';
}
}return fetchData() returns the still-pending Future immediately. The try block ends before that Future completes. Write return await fetchData() when the surrounding try must catch its error.
A similar mistake is starting a Future without awaiting or handling it:
Future<void> save() async {
throw Exception('save failed');
}
Future<void> main() async {
unawaited(save());
print('continue');
}unawaited documents that the Future is intentionally ignored, but its error still needs a deliberate design. If failure matters, use await save() inside try/catch. If the operation should run in the background, give it an error handler rather than allowing an uncaught error.
Exercise
Why must return await fetchData() be used inside a try block when the block needs to catch errors from fetchData?
Show answer
await keeps execution at the try block until the Future completes, so its error is rethrown inside that block. Without await, the pending Future leaves the block before it fails.