Dart Async Error Handling
An error from an awaited Future can be caught with try and catch. A chain error can be caught with catchError instead.
Catching an awaited error
The awaited Future completes with an error, so catch runs. The line after the block prints as well.
Future<void> main() async {
try {
await Future.error('load failed');
} catch (e) {
print('caught the failure');
}
print('program continues');
}A throw caught by the caller
riskyScore throws instead of returning a score. The caller catches the throw at its await.
Future<int> riskyScore() async {
throw 'score missing';
}
Future<void> main() async {
try {
var score = await riskyScore();
print(score);
} catch (e) {
print('caller caught it');
}
}An error inside a chain
The then step calls failStep, and failStep throws. catchError turns the error into a fallback value that prints.
String failStep(int value) {
throw 'step broke';
}
Future<void> main() async {
var label = await Future.value(5)
.then((v) => failStep(v))
.catchError((e) => 'fallback label');
print(label);
}When the await succeeds
The awaited value arrives, so catch never runs. The value and the closing line both print.
Future<void> main() async {
try {
var word = await Future.value('ready');
print(word);
} catch (e) {
print('caught the failure');
}
print('done');
}Example
Future<String> loadTitle() async {
throw 'title missing';
}
Future<void> main() async {
try {
var title = await loadTitle();
print(title);
} catch (e) {
print('using untitled');
}
var backup = await Future.value('draft')
.then((v) => v.toUpperCase())
.catchError((e) => 'none');
print(backup);
}Key points
- A try block can wrap an await that might fail.
- catch runs when the awaited Future completes with an error.
- Code after the try and catch block runs after a caught error.
- An async function can throw to signal that its work failed.
- The caller catches that throw at its own await.
- catchError at the end of a then chain catches an error raised inside the chain.
- Every program in this lesson catches its error, so each one ends normally.
In this example, loadTitle throws, and the catch block prints using untitled. The chain after it succeeds, so catchError never runs. The last print shows DRAFT in capital letters.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What happens after a catch block handles an awaited error?