Dart Exception Handling

Dart uses try, catch, finally, and on for exception handling.

Basic Try-Catch

Dart
try {
  final result = int.parse('abc');
} catch (e) {
  print('Error: $e');
}

Catching Specific Exceptions

Dart
try {
  final file = File('data.txt');
  final contents = await file.readAsString();
} on FileSystemException catch (e) {
  print('File error: ${e.message}');
} catch (e) {
  print('Unknown error: $e');
}

Custom Exceptions

Dart
class InsufficientFundsException implements Exception {
  final double balance;
  final double amount;

  InsufficientFundsException(this.balance, this.amount);

  @override
  String toString() =>
      'Cannot withdraw Rs. $amount: balance is Rs. $balance';
}

Tips

  • Use on to catch specific exception types before generic catch.
  • Always clean up resources in finally.
  • Throw exceptions for truly exceptional conditions, not normal flow.

🎉 You have completed the Dart course!