Error & Exception Handling: try, catch, on, finally & rethrow
1Concept
Dart uses try, on <Type> catch (e, stackTrace) to catch specific exception types, and finally for guaranteed execution. rethrow propagates exceptions up the call chain.
2Architecture Diagram
try {
throw FormatException('Invalid JSON');
} on FormatException catch (e) {
// Specific catch handler
} catch (e, stack) {
// Catch-all with stack trace
} finally {
// Always executes
}3Code Example
Stage 0 Language Foundations
class AuthException implements Exception {
final String message;
AuthException(this.message);
@override
String toString() => 'AuthException: $message';
}
void login(String username) {
if (username.isEmpty) {
throw AuthException('Username cannot be empty.');
}
print('Logged in as $username');
}
void main() {
try {
login('');
} on AuthException catch (e) {
print('[Handled] $e');
} catch (e, stack) {
print('[Unexpected] $e');
} finally {
print('Auth sequence completed.');
}
}4Expected Output
[Handled] AuthException: Username cannot be empty. Auth sequence completed.
5Key Takeaways
- ✓Use 'on SpecificType catch (e)' to handle specific exception types.
- ✓stackTrace captures full call stack history.
- ✓Finally blocks always execute even if exceptions are thrown.