Summary - Advanced error handling
- Dart course
- Intermediate
- Lesson 105/116
- 5 min
Combine hierarchy, Result and async errors to write a robust service.
Summary - Advanced error handling
In this group you learned advanced error handling: Exception hierarchy, Error vs Exception, Stack trace, Result pattern and async error handling.
Summary: custom exceptions by extending Exception; not catching Error; StackTrace with catch (e, s); type-safe errors with sealed Result; Future errors with async/await.
The right tool: Exception (or Result) for expected conditions, Error fixes for programmer mistakes.
A combined example
A function combining everything: AppException extends Exception, Future<int> fetchCount() async { throw AppException('timeout'); }.
The caller: try { await fetchCount(); } on AppException catch (e) { print(e.message); }. Here async error + custom exception + message access come together.
This pattern is common in real apps: a network call throws a custom exception, caught with async/await.
Practice Combined error handling
Define an AppException class (extends Exception, final String message + constructor). Write Future<int> fetchCount() async { throw AppException('timeout'); }. Make main async: call it with try { await fetchCount(); } on AppException catch (e) { print(e.message); }.
Starter code
// Define the AppException class
// Write the fetchCount function
void main() async {
// call fetchCount, catch AppException
}Sample solution
class AppException extends Exception {
final String message;
AppException(this.message);
}
Future<int> fetchCount() async {
throw AppException('timeout');
}
void main() async {
try {
await fetchCount();
} on AppException catch (e) {
print(e.message);
}
}Expected output
timeout
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is part of the Result pattern?
- Error and Exception
- try and catch
- throw and rethrow
- Success and Failure Correct answer
Explanation: Result consists of Success and Failure subclasses.
2 Error handling summary
| Term | Meaning |
|---|---|
extends Exception |
Custom exception |
catch (e, s) |
StackTrace |
Result<T> |
Type-safe |
await + catch |
Async error |
3 The rethrow keyword
try { risky(); } catch (e) { ____; }
try { risky(); } catch (e) { rethrow; }
Explanation: rethrow rethrows the caught error.