Sub topic 13
Handling errors with exceptions
This chapter assumes you know Dart functions, classes, and control flow from earlier chapters. You should also know what a Future is, at least at a basic level. Here you will learn how Dart reports and handles runtime errors: throw, try, on, catch, finally, rethrow, custom exception classes, and the difference between Exception and Error.
How exceptions work in Dart
An exception is an object thrown when something goes wrong. Throwing stops the current function and unwinds the call stack until a matching catch or on clause handles it. If nothing handles it, the program (or the current isolate) ends with an error report.
Dart has no checked exceptions. A function signature never lists what it can throw, and the compiler never forces you to catch anything. Documentation and tests carry that information.
You can throw any object, including a string:
void main() {
try {
throw 'just a string';
} catch (e) {
print(e);
}
}Throwing non-Exception objects is legal but discouraged. A string carries no type to match on and no stack-trace conventions. Throw an Exception, an Error subtype, or your own class.
Exception versus Error
The core library separates two families.
| Family | Meaning | Typical examples | Should you catch it? |
|---|---|---|---|
| `Exception` | A recoverable condition that the program can anticipate | `FormatException`, `TimeoutException`, `IOException` | Yes, where you can recover or report |
| `Error` | A bug in the program | `ArgumentError`, `StateError`, `RangeError`, `TypeError`, `UnimplementedError` | Rarely. Fix the code instead |
Exception is an interface, so a class declares implements Exception. Error is a class you can extend. An Error usually means a caller broke a contract, such as passing an invalid argument or reading past the end of a list. Catching it hides the bug.
try, on, catch, and finally
int parseAge(String input) {
final age = int.tryParse(input);
if (age == null) {
throw FormatException('Not a number', input);
}
if (age < 0) {
throw ArgumentError.value(age, 'age', 'must not be negative');
}
return age;
}
void main() {
for (final text in ['42', 'abc', '-1']) {
try {
print(parseAge(text));
} on FormatException catch (e) {
print('Bad format: ${e.message} (${e.source})');
} on ArgumentError catch (e) {
print('Bad argument: ${e.message}');
}
}
}This prints 42, then Bad format: Not a number (abc), then Bad argument: must not be negative.
The pieces work like this:
on Typematches by type and does not bind the object.on Type catch (e)matches by type and binds the exception toewith that static type, so you can reade.messageande.source.catch (e)with noonmatches everything, including non-Exceptionobjects.ehas typeObject.catch (e, stack)also binds theStackTrace.- Clauses are checked from top to bottom. The first match wins, so list specific types before general ones.
finallyalways runs, whether thetryblock finished normally, threw, or returned.
Clause order matters
If you write on Exception above on FormatException, the second clause can never run, because every FormatException is already an Exception. The analyzer reports the unreachable clause, so run dart analyze regularly.
finally and return
A finally block runs even when the try block executes return. Use it for cleanup such as closing files, cancelling timers, or hiding a spinner. Avoid return inside finally, because it replaces any pending exception and hides the failure.
Rethrowing and custom exceptions
Sometimes you want to log an error and let a caller deal with it. Use rethrow, which preserves the original stack trace.
class InsufficientFundsException implements Exception {
final double needed;
const InsufficientFundsException(this.needed);
@override
String toString() => 'InsufficientFundsException: need $needed more';
}
double withdraw(double balance, double amount) {
if (amount > balance) throw InsufficientFundsException(amount - balance);
return balance - amount;
}
void main() {
try {
try {
withdraw(50, 80);
} on InsufficientFundsException catch (e, stack) {
print('Logging: $e');
print('Has stack trace: ${stack.toString().isNotEmpty}');
rethrow;
} finally {
print('cleanup');
}
} on Exception catch (e) {
print('Outer caught: $e');
}
}The output order is: Logging: ..., Has stack trace: true, cleanup, then Outer caught: .... The inner finally runs before the outer handler, because the exception only continues to unwind after the inner try statement is finished.
Custom exceptions should be small data classes. Implement Exception, store the facts a handler needs as final fields, and override toString so uncaught reports are readable. Name them after the failure (InsufficientFundsException), not the layer that threw them.
rethrow versus throw e
Inside a catch block, throw e throws the same object again but starts a new stack trace at that line. rethrow keeps the original trace, which shows where the failure actually happened. Prefer rethrow for pass-through handling.
If you want to wrap a low-level failure in a higher-level one, throw a new exception that holds the cause. Use Error.throwWithStackTrace(newError, stack) to keep the original trace attached.
class ConfigException implements Exception {
final String message;
final Object cause;
const ConfigException(this.message, this.cause);
@override
String toString() => 'ConfigException: $message (cause: $cause)';
}
int readPort(String raw) {
try {
return int.parse(raw);
} on FormatException catch (e, stack) {
Error.throwWithStackTrace(ConfigException('Invalid port "$raw"', e), stack);
}
}
void main() {
try {
readPort('80x');
} on ConfigException catch (e) {
print(e);
}
}Dart accepts this version of readPort because Error.throwWithStackTrace is declared to return Never. The compiler knows that code path cannot fall through, so no return is needed after it.
How an exception travels
Errors in asynchronous code
When you await a future that fails, the exception is rethrown at the await expression. The same try and on syntax works there.
Future<int> risky() async {
await Future.delayed(const Duration(milliseconds: 50));
throw StateError('boom');
}
Future<void> main() async {
try {
print(await risky());
} on StateError catch (e) {
print('Caught: ${e.message}');
} finally {
print('done');
}
}The handler only sees errors from futures that are awaited inside the try. If you call risky() without await, the try finishes first and a later failure is reported as an unhandled asynchronous error. The next chapters cover futures and streams in detail.
Common mistakes
- Bare
catch (e)everywhere. It catchesErrorsubtypes such asTypeError, and it hides bugs. Preferon SomeException. If you need a catch-all at a boundary, such as the top of a request handler, log the error and the stack trace. - Swallowing errors. An empty
catchblock makes failures invisible. Handle the error, log it, or rethrow it. - Using exceptions for normal flow. Prefer
int.tryParseand a null check overtry { int.parse(...) }when bad input is expected. Exceptions suit exceptional cases. - Catching
Errorto "fix" a bug. ARangeErrormeans the index logic is wrong. Correct the logic. - Misordered
onclauses. General types above specific ones make the specific handler dead code. - Losing the stack trace. Write
rethrow, notthrow e, when passing an error through.
Choosing a strategy
- If the caller can reasonably fix the problem, throw an
Exceptionsubclass with the facts needed to recover. - If the caller broke a rule, throw an
ArgumentErrororStateError, and let it surface during development. - If failure is a common outcome, return a nullable value or a result type instead of throwing.
- Catch narrowly, as close to the recovery point as possible, and use
finallyfor cleanup.
Exercise
What does this program print, and in what order? void main() { try { try { throw FormatException('bad'); } on ArgumentError { print('A'); } finally { print('B'); } } on FormatException { print('C'); } finally { print('D'); } }
Show answer
It prints B, C, D, one per line. The inner on ArgumentError does not match a FormatException, so no handler in the inner try runs. The inner finally prints B while the exception keeps unwinding. The outer on FormatException matches and prints C, and the outer finally prints D last.
Exercise
A colleague writes on Exception catch (e) { log(e); throw e; } to log and pass an error upward. What is the problem, and what is the fix?
Show answer
throw e starts a new stack trace at that line, so the trace no longer shows where the failure originated. Replace it with rethrow;, which keeps the original stack trace.