TExcelTAD
Home › Dart › Dart Exceptions

Dart Exceptions

Things go wrong: files are missing, input is malformed, a network request fails. Dart signals such problems by throwing an object, and you handle them with try, on, catch and finally. Unlike Java, Dart has no checked exceptions — functions don't declare what they throw, so documenting it is up to you.

Exception vs Error

Kind Meaning Should you catch it?
Exception An expected, recoverable failure (bad input, I/O problems) Yes — handle it
Error A programming bug (RangeError, TypeError, StateError, ArgumentError) Usually no — fix the code

Common built-in types: FormatException, IOException, TimeoutException (exceptions); ArgumentError, RangeError, StateError, UnsupportedError, UnimplementedError (errors).

try / on / catch / finally

dart · try it yourself
int parseQuantity(String input) {
  final n = int.parse(input); // throws FormatException on bad input
  if (n <= 0) throw ArgumentError.value(n, 'quantity', 'must be positive');
  return n;
}

void main() {
  for (final raw in ['3', 'abc', '-2']) {
    try {
      final q = parseQuantity(raw);
      print('ok: $q');
    } on FormatException catch (e) {
      print('not a number: ${e.source}');
    } on ArgumentError catch (e) {
      print('invalid: ${e.message} (${e.invalidValue})');
    } finally {
      print('  checked "$raw"');
    }
  }
}
ok: 3
  checked "3"
not a number: abc
  checked "abc"
invalid: must be positive (-2)
  checked "-2"
Clause Purpose
on Type Catch only that type (without access to the object)
on Type catch (e) Catch that type and bind it to e
catch (e) Catch anything
catch (e, s) Also bind the StackTrace
finally Always runs — success, failure or return

Clauses are checked top to bottom, so put specific types before general ones.

Throwing

You can throw any non-null object, but by convention you throw Exception or Error subclasses. throw is an expression, so it fits in arrow functions and ??:

dart · try it yourself
class Wallet {
  int _balance = 0;
  int get balance => _balance;

  void deposit(int amount) =>
      amount > 0 ? _balance += amount : throw ArgumentError('amount must be > 0');

  void withdraw(int amount) {
    if (amount > _balance) {
      throw StateError('insufficient funds: balance $_balance, wanted $amount');
    }
    _balance -= amount;
  }
}

void main() {
  final w = Wallet()..deposit(50);
  try {
    w.withdraw(80);
  } on StateError catch (e) {
    print(e.message);
  }

  final config = <String, String>{};
  try {
    final port = config['port'] ?? (throw Exception('port missing'));
    print(port);
  } catch (e) {
    print(e);
  }
}
insufficient funds: balance 50, wanted 80
Exception: port missing

Custom exceptions

Implement Exception and give your class useful fields and a readable toString:

dart · try it yourself
class PaymentException implements Exception {
  final String code;
  final String message;
  const PaymentException(this.code, this.message);

  @override
  String toString() => 'PaymentException[$code]: $message';
}

void pay(int cents, String card) {
  if (card.length != 16) throw const PaymentException('CARD', 'invalid card number');
  if (cents > 100000) throw const PaymentException('LIMIT', 'amount over limit');
  print('paid $cents');
}

void main() {
  final attempts = [(500, '1234567812345678'), (500, '42'), (200000, '1234567812345678')];
  for (final (amount, card) in attempts) {
    try {
      pay(amount, card);
    } on PaymentException catch (e) {
      print(e);
      if (e.code == 'LIMIT') print('  -> ask for approval');
    }
  }
}
paid 500
PaymentException[CARD]: invalid card number
PaymentException[LIMIT]: amount over limit
  -> ask for approval

Rethrowing

Sometimes you want to react (log, clean up) but let the caller handle the problem. rethrow re-raises the same exception and preserves the original stack trace:

dart · try it yourself
void loadUser(int id) {
  try {
    if (id < 0) throw FormatException('bad id $id');
    print('user $id loaded');
  } catch (e) {
    print('log: $e');
    rethrow;
  }
}

void main() {
  try {
    loadUser(7);
    loadUser(-1);
  } on FormatException catch (e) {
    print('caller handled: ${e.message}');
  }
}
user 7 loaded
log: FormatException: bad id -1
caller handled: bad id -1

Good practices

  • Catch specific types with on. A bare catch (e) also swallows bugs like TypeError.
  • Don't catch Errors to hide them — they mean the code is wrong.
  • Use finally (or try/finally without catch) to release resources.
  • Prefer returning null or a result type for expected outcomes (int.tryParse), and exceptions for exceptional ones.
  • Async code uses the same try/catch with await — see Error Handling with Futures.

Test yourself

Which clause catches only FormatException and gives you the object?

  1. catch (FormatException e)
  2. on FormatException catch (e)
  3. except FormatException as e
  4. on FormatException (e)

What is the main difference between Exception and Error in Dart?

  1. Errors are faster
  2. Exceptions are recoverable failures; errors indicate programming bugs
  3. Errors can't be thrown
  4. Exceptions must be declared in the function signature

Why use rethrow instead of throw e?

  1. It is shorter only
  2. It preserves the original stack trace
  3. It converts the error to an Exception
  4. It suppresses the exception