TExcelTAD
Home › Flutter › Dart Error Handling

Dart Error Handling

Things go wrong: a server is down, a file is missing, a user types "abc" where a number belongs. Dart signals such problems by throwing an object, and you catch it to recover. Good error handling is what separates an app that crashes from one that shows a friendly "Try again" button.

Exceptions vs errors

Dart distinguishes two families of throwable objects:

Kind Base type Meaning Should you catch it?
Exception Exception An expected problem at runtime (bad input, network failure) Yes — handle it
Error Error A bug in the program (index out of range, null check failed) Usually no — fix the code

Common built-in types include FormatException, IOException, TimeoutException (exceptions) and RangeError, ArgumentError, StateError, TypeError (errors).

try, catch and finally

dart · try it yourself
void main() {
  final inputs = ['42', '3.5', 'abc'];

  for (final text in inputs) {
    try {
      final n = int.parse(text);
      print('Parsed $n');
    } on FormatException catch (e) {
      print('Not an integer: "${e.source}"');
    } finally {
      print('-- checked "$text"');
    }
  }
}
Parsed 42
-- checked "42"
Not an integer: "3.5"
-- checked "3.5"
Not an integer: "abc"
-- checked "abc"
  • on Type catches only that type.
  • catch (e) gives you the thrown object; catch (e, s) also gives the stack trace.
  • finally always runs — whether the block succeeded, threw, or returned. Use it for cleanup.

Catching several types

You can chain several on clauses. They are checked in order, so put the most specific types first and a general catch last.

dart · try it yourself
int safeDivide(int a, int b) {
  if (b == 0) throw ArgumentError('b must not be zero');
  return a ~/ b;
}

void tryIt(void Function() action) {
  try {
    action();
  } on RangeError {
    print('Index out of range');
  } on ArgumentError catch (e) {
    print('Bad argument: ${e.message}');
  } catch (e) {
    print('Something else: $e');
  }
}

void main() {
  tryIt(() => print(safeDivide(10, 3)));
  tryIt(() => safeDivide(1, 0));
  tryIt(() => [1, 2, 3][10]);
  tryIt(() => throw 'a plain string');
}
3
Bad argument: b must not be zero
Index out of range
Something else: a plain string

RangeError (and IndexError, thrown by [1, 2, 3][10]) is a subclass of ArgumentError. That's why the on RangeError clause must come first — if on ArgumentError were listed first, it would catch the index error too.

Tip: Dart lets you throw any object (even a string), but you should throw Exception or Error subclasses so callers can catch them precisely.

Custom exceptions

Create your own exception classes to describe domain problems. Implement Exception and give it a useful toString.

dart · try it yourself
class InsufficientFundsException implements Exception {
  final double needed;
  InsufficientFundsException(this.needed);

  @override
  String toString() => 'InsufficientFundsException: need $needed more';
}

class Wallet {
  double balance;
  Wallet(this.balance);

  void pay(double amount) {
    if (amount > balance) {
      throw InsufficientFundsException(amount - balance);
    }
    balance -= amount;
  }
}

void main() {
  final w = Wallet(50);
  try {
    w.pay(30);
    print('Paid 30, left ${w.balance}');
    w.pay(40);
    print('This line is never reached');
  } on InsufficientFundsException catch (e) {
    print(e);
    print('Missing: ${e.needed}');
  }
}
Paid 30, left 20.0
InsufficientFundsException: need 20.0 more
Missing: 20.0

Rethrowing

Sometimes you want to log an error but still let it propagate. Use rethrow, which keeps the original stack trace.

dart · try it yourself
void loadConfig() {
  try {
    throw const FormatException('missing "}" at line 3');
  } catch (e) {
    print('loadConfig: logging $e');
    rethrow;
  }
}

void main() {
  try {
    loadConfig();
  } on FormatException catch (e) {
    print('main: showing message "${e.message}"');
  }
}
loadConfig: logging FormatException: missing "}" at line 3
main: showing message "missing "}" at line 3"

Errors in async code

With async/await, errors from futures are thrown at the await and caught by the surrounding try. Without await, use .catchError or the onError callback.

dart · try it yourself
Future<String> fetchProfile(bool online) async {
  await Future.delayed(const Duration(milliseconds: 10));
  if (!online) throw StateError('No connection');
  return 'Profile loaded';
}

Future<void> main() async {
  try {
    print(await fetchProfile(true));
    print(await fetchProfile(false));
  } on StateError catch (e) {
    print('Caught: ${e.message}');
  }

  final fallback = await fetchProfile(false).catchError((_) => 'Cached profile');
  print(fallback);
}
Profile loaded
Caught: No connection
Cached profile

Result types instead of exceptions

For expected failures, some teams prefer returning a value that describes success or failure, using a sealed class. The compiler then forces callers to handle both cases:

dart
sealed class Result<T> {}
class Ok<T> extends Result<T> { Ok(this.value); final T value; }
class Err<T> extends Result<T> { Err(this.message); final String message; }

String show(Result<int> r) => switch (r) {
  Ok(:final value) => 'Value $value',
  Err(:final message) => 'Error $message',
};

In Flutter, catch exceptions close to where you can do something useful — for example, in the code that loads data for a screen — and turn them into an error state the UI can display.

Test yourself

Which block always runs, whether or not an exception was thrown?

  1. catch
  2. on
  3. finally
  4. rethrow

What does rethrow do?

  1. Throws a new copy of the error
  2. Re-throws the caught error, keeping its stack trace
  3. Retries the try block
  4. Ignores the error

Which type should your own domain exception usually implement?

  1. Error
  2. Exception
  3. String
  4. Object only