Async errors
- Dart course
- Intermediate
- Lesson 104/116
- 5 min
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
// Define the fetchUser function
void main() async {
// call fetchUser with await, catch the error
}Sample solution
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
try { await fetch(); } ____ (e) { print(e); }
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.