Explain it simply
Sealed types and error handling in plain language
A sealed class is a class whose family members can be counted. If the subtypes of a sealed class Outcome are Valid and Invalid, the compiler knows exactly those two, so it can check on its own whether a switch handles both. Nobody has to double-check by hand that no case is missing.
Error handling is what happens when something goes wrong: you throw an object and catch it with try/catch. Both halves serve one aim, making variation and failure visible in the code instead of hiding them.
Problem → Why → Solution
The problem: flags that allow impossible states
A screen has three situations: loading, ready (with a list of items) and failed (with a message). The usual approach is one class with bool isLoading, String? error and List<String>? items. Those three fields allow eight combinations, only three of which are meaningful, and nothing stops isLoading from being true while an error is set.
Error-handling code goes wrong in the same quiet way: an empty try { ... } catch (e) { } swallows genuine bugs and expected failures alike, and nobody can tell why something stopped working.
class ScreenState {
bool isLoading = true;
String? error;
List<String>? items;
}
String label(ScreenState s) {
if (s.isLoading) return 'Loading';
if (s.error != null) return 'Error: ${s.error}';
return 'Ready: ${s.items!.length}'; // crashes if items is null: a state nobody meant
}
void save() {
try {
// ...write to disk...
} catch (e) {
// ignored: a typo here would vanish without a trace
}
}Make impossible states unrepresentable
Flags and nullable fields allow combinations that cannot exist, which is why s.items! needs a ! to cope. A sealed hierarchy gives each state its own type holding only the data that state needs, so Failed has no items and Ready has no error, and the compiler insists that every switch handles every case.
Core concept: sealed, exhaustiveness, Exception and Error
Declaring sealed class Outcome {} means Outcome itself cannot be instantiated (like an abstract class) and only classes in the same library may extend or implement it, so the compiler knows every subtype. A switch over Outcome must handle each subtype with its own case, and a missing one is a compile error. Subtypes can carry their own fields, which patterns pull apart as in Valid(age: var a). A generic sealed class such as Result<T> is fine too.
In Dart you can throw any object, but by convention there are two families. An Exception is a recoverable condition the caller may handle (FormatException, your own custom exception), while an Error is a bug in the program (ArgumentError, StateError, RangeError, TypeError) that you should fix rather than catch and hide. You write your own as class MyProblem implements Exception; you cannot extend Exception (as lesson 16 showed).
Code in a try block runs until something throws, which leaves the function immediately and checks the catch clauses from the top. on Type filters by type (on FormatException catch (e)) and the first match runs; in catch (e, st) the second parameter is the stack trace. finally always runs, whether the block succeeded, failed or even executed a return. rethrow throws the caught exception again with its original stack trace.
An exception that no catch handles stops the program: dart run prints "Unhandled exception:" to stderr and exits with code 255 (reproduced). So handle recoverable failures and let bugs surface, and when a failure is a normal outcome you want to return, use a sealed type such as Result.
| Exception | Error | |
|---|---|---|
| Meaning | A condition the caller can handle | A bug in the program |
| Examples | FormatException, your own exceptions | ArgumentError, StateError, RangeError |
| Usual handling | Catch, recover or report | Fix the code; log at the top level only |
- Sealed: the family is closed
- A switch must cover every member
- throw leaves the current function
- on picks a handler; finally always runs
A new subtype breaks every un-updated switch at compile time, but a new exception type only matters to handlers written for it.
General pattern
sealed class Name {}
class CaseA extends Name { CaseA(this.data); final Type data; }
class CaseB extends Name {}
Result f(Name n) => switch (n) {
CaseA(:var data) => value,
CaseB() => value,
};
class Problem implements Exception { Problem(this.detail); final String detail; }
try {
risky();
} on Problem catch (e, stack) { handle(e); rethrow; }
finally { cleanup(); }A sealed class closes the set of subtypes and the switch must list every case. A custom exception implements Exception, the try block catches it by type with on, and finally performs the cleanup.
Worked example: validating ages and returning a sealed outcome
parseAge throws an InvalidAge exception for bad input. check catches it and turns the result into the sealed type Outcome (Valid or Invalid), so the rest of the code no longer deals with exceptions. The checked lines in the output show the finally block running every time.
// An Exception: a problem the caller can reasonably handle.
class InvalidAge implements Exception {
InvalidAge(this.input, this.reason);
final String input;
final String reason;
@override
String toString() => 'InvalidAge("$input": $reason)';
}
int parseAge(String input) {
final age = int.tryParse(input.trim());
if (age == null) throw InvalidAge(input, 'not a number');
if (age < 0 || age > 150) throw InvalidAge(input, 'out of range');
return age;
}
// A sealed type: the compiler knows every possible subtype.
sealed class Outcome {}
class Valid extends Outcome {
Valid(this.age);
final int age;
}
class Invalid extends Outcome {
Invalid(this.error);
final InvalidAge error;
}
Outcome check(String input) {
try {
return Valid(parseAge(input));
} on InvalidAge catch (e) {
return Invalid(e);
} finally {
print('checked "$input"');
}
}
// Exhaustive: delete a case and this stops compiling.
String report(Outcome outcome) => switch (outcome) {
Valid(age: var a) when a >= 18 => 'adult, $a',
Valid(age: var a) => 'minor, $a',
Invalid(error: InvalidAge(reason: var r)) => 'rejected: $r',
};
void main() {
for (final input in ['42', '12', 'abc', '200']) {
print(report(check(input)));
}
}Code breakdown
- Custom exception
class InvalidAge implements Exception {Implementing Exception lets callers catch it with on InvalidAge, and it carries the input and the reason as fields. You cannot extend Exception.
- Throw
if (age == null) throw InvalidAge(input, 'not a number');int.tryParse returns null instead of throwing, so the function throws its own exception. Once throw runs, the rest of parseAge is skipped.
- Catch by type
} on InvalidAge catch (e) {Only InvalidAge is caught here. Any other throwable, such as an Error caused by a bug, skips this clause and keeps travelling upward.
- Finally
print('checked "$input"');The print in finally runs after return Valid(...) and after return Invalid(e) alike. Cleanup such as closing a file or releasing a connection belongs here.
- Sealed type
sealed class Outcome {}The compiler knows the only subtypes of Outcome are Valid and Invalid, and no class outside this library may extend it.
- Guard and nested pattern
Invalid(error: InvalidAge(reason: var r)) => 'rejected: $r',The pattern opens the error inside Invalid and pulls its reason out as r. Two Valid cases are split with a when guard, and the three cases together cover Outcome completely.
checked "42"
adult, 42
checked "12"
minor, 12
checked "abc"
rejected: not a number
checked "200"
rejected: out of rangeException or Error: what to catch and how
The attempt function below classifies what was thrown. It puts on Exception before on Error and ends with a plain catch (e), which picks up objects that are neither an Exception nor an Error, such as a string. int.parse throws a FormatException, a missing list index a RangeError, and first on an empty list a StateError.
class InvalidAge implements Exception {}
void attempt(String label, void Function() action) {
try {
action();
print('$label: ok');
} on Exception catch (e) {
print('$label: Exception -> ${e.runtimeType}');
} on Error catch (e) {
print('$label: Error -> ${e.runtimeType}');
} catch (e) {
print('$label: other -> $e');
}
}
void main() {
attempt('parse', () => int.parse('abc'));
attempt('index', () => <int>[1][5]);
attempt('state', () => <int>[].first);
attempt('argument', () => throw ArgumentError('bad'));
attempt('custom', () => throw InvalidAge());
attempt('string', () => throw 'just a string');
}parse: Exception -> FormatException
index: Error -> RangeError
state: Error -> StateError
argument: Error -> ArgumentError
custom: Exception -> InvalidAge
string: other -> just a stringCatching index with only on Exception would miss it, because RangeError is not an Exception. That is deliberate: a bug should not be hidden where it cannot be fixed. Throwing a non-Exception object such as throw 'just a string' works, but the catching side then has no useful type to select on, so avoid it.
try, catch, finally and rethrow in order
The process function parses its input and, on a FormatException, records it and sends it back up with rethrow, while finally always does the cleanup. The caller in main catches it once more. The output shows the exact order of events.
void process(String input) {
try {
print('start $input');
final n = int.parse(input);
print('parsed $n');
} on FormatException catch (e) {
print('bad format: ${e.message}');
rethrow; // same exception, same stack trace
} finally {
print('cleanup $input');
}
}
int f() {
try {
return 1;
} finally {
print('cleanup'); // runs before f() actually returns
}
}
void main() {
for (final s in ['7', 'x7']) {
try {
process(s);
} catch (e) {
print('caller saw ${e.runtimeType}');
}
}
print(f());
}start 7
parsed 7
cleanup 7
start x7
bad format: Invalid radix-10 number
cleanup x7
caller saw FormatException
cleanup
1Two things to notice. First, inside a catch use rethrow rather than throw e: rethrow keeps the original stack trace, so you can still find where the failure began. Second, finally ran even though f() had already hit return 1, so cleanup prints before 1. The message above comes from the FormatException's message property.
A sealed generic Result<T> and when to throw instead
When failure is an ordinary outcome, as with parsing text a user typed, you do not need to throw: return a sealed Result<T> instead. The switch forces the caller to handle both ok and error. Declaring Ok and Err as final class also stops code outside this library from extending them.
sealed class Result<T> {}
final class Ok<T> extends Result<T> {
Ok(this.value);
final T value;
}
final class Err<T> extends Result<T> {
Err(this.message);
final String message;
}
Result<int> parseInt(String text) {
final n = int.tryParse(text);
return n == null ? Err('"$text" is not a number') : Ok(n);
}
String show(Result<int> r) => switch (r) {
Ok(:var value) => 'ok $value',
Err(:var message) => 'error: $message',
};
void main() {
print(show(parseInt('12')));
print(show(parseInt('1x')));
final results = [parseInt('1'), parseInt('2'), parseInt('z')];
final oks = results.whereType<Ok<int>>().map((r) => r.value).toList();
print(oks);
}| Situation | Prefer |
|---|---|
| Failure is a normal outcome the caller handles right away | A sealed type such as Result |
| An unexpected condition that must travel up several layers | Throw an Exception |
| A bug in the program itself | Throw an Error (ArgumentError, StateError) |
When a switch over a sealed type misses a subtype, the compiler names the leftover one: adding Skipped to Outcome while a switch handles only Valid() and Invalid() gives "The type 'Outcome' is not exhaustively matched by the switch cases since it doesn't match 'Skipped()'." (reproduced). That error finds every switch you still have to update, automatically.
In real projects
Where sealed types and error handling show up in real projects
In apps, a network call has three situations, loading, data and error, which a sealed type captures and the UI renders with a switch. When a new state such as empty is added, the compiler points at every screen not yet updated. For error handling, the key habit is to catch at each layer only what that layer is responsible for.
- API layers: turn HTTP failures into your own sealed failure type (NetworkFailure, NotFound, ServerError) so the UI switches on it without knowing any package's exception types.
- Input parsing: handle JSON and form input with int.tryParse or functions that return a Result; not using exceptions for ordinary failures reads more cleanly.
- Logging and crash reporting: use catch (e, st) at the top to record the error with its stack trace and rethrow unexpected Errors.
Common mistakes
Common mistakes with sealed types and error handling
Catching everything with catch (e) and hiding it
try { ... } catch (e) { } catches a RangeError or StateError along with the FormatException, so bugs vanish. Name only the type you can handle, as in on FormatException catch (e), and let everything else keep travelling.
Using exceptions as control flow for ordinary outcomes
try { int.parse(text) } on FormatException { ... } is clumsy when bad text is a normal occurrence. int.tryParse(text) returning null, or a function returning a Result, is shorter and pushes the caller to handle both cases.
Throwing something that is not an Exception
throw 'out of stock'; compiles, but the catching side can only write on String, which carries no meaning (the example above showed other -> just a string), so nobody can select it precisely. Write your own type: class OutOfStock implements Exception.
Putting cleanup only on the success path
Putting file.close() as the last line of the try block means it never runs when something throws halfway, and the resource leaks. Move cleanup into finally, which also runs after a return or a throw.
Best practices
Best practices
- Do not add _ to a switch over a sealed type, so you keep getting the compiler's warning when a subtype is added.
- Write custom exceptions with implements Exception and give them the fields a handler needs (input, reason), plus a clear toString.
- Use on to catch only the types you can handle, and keep a bare catch (e) for top-level logging.
- Release resources in finally and use rethrow rather than throw e.
Mini challenge
Mini challenge: a withdrawal outcome
Write a withdrawal function. A zero or negative amount throws an ArgumentError (a bug), and an insufficient balance throws your own InsufficientFunds exception. tryWithdraw must catch only InsufficientFunds and turn the result into a sealed WithdrawResult (Done or Refused), letting the ArgumentError keep travelling.
- InsufficientFunds implements Exception and has a shortBy field
- withdraw(balance, amount) throws ArgumentError.value for amount <= 0 and InsufficientFunds when short, otherwise returns the new balance
- sealed class WithdrawResult has Done(balance) and Refused(reason); tryWithdraw catches only InsufficientFunds and increments an attempt counter in finally
- show is an exhaustive switch expression; in main, call with -5 and catch the ArgumentError separately
// TODO 1: class InsufficientFunds implements Exception, with a `shortBy` field
// TODO 2: double withdraw(double balance, double amount)
// - amount <= 0 is a bug: throw ArgumentError.value(...)
// - amount > balance: throw InsufficientFunds(amount - balance)
// - otherwise return the new balance
// TODO 3: sealed class WithdrawResult with Done(balance) and Refused(reason)
var attempts = 0;
// TODO 4: WithdrawResult tryWithdraw(double balance, double amount)
// catch ONLY InsufficientFunds; count every call in finally
// TODO 5: String show(WithdrawResult r) as an exhaustive switch expression
void main() {
// TODO 6: withdraw 30 from 100, then 150 from 100, then -5 from 100;
// catch the ArgumentError from the last call and print its message,
// then print how many attempts were made
}Expected: Running it should print: Done: 70.0 Refused: need 50.0 more bug caught: must be positive attempts: 3
Show hint
Shape tryWithdraw as try { return Done(withdraw(...)); } on InsufficientFunds catch (e) { return Refused('need ${e.shortBy} more'); } finally { attempts++; }. With no on clause for ArgumentError it skips past and reaches main, yet finally still runs, so attempts ends at 3. The message of ArgumentError.value(amount, 'amount', 'must be positive') is 'must be positive'.
Show solution
class InsufficientFunds implements Exception {
InsufficientFunds(this.shortBy);
final double shortBy;
@override
String toString() => 'InsufficientFunds(short by $shortBy)';
}
double withdraw(double balance, double amount) {
if (amount <= 0) {
throw ArgumentError.value(amount, 'amount', 'must be positive');
}
if (amount > balance) throw InsufficientFunds(amount - balance);
return balance - amount;
}
sealed class WithdrawResult {}
class Done extends WithdrawResult {
Done(this.balance);
final double balance;
}
class Refused extends WithdrawResult {
Refused(this.reason);
final String reason;
}
var attempts = 0;
WithdrawResult tryWithdraw(double balance, double amount) {
try {
return Done(withdraw(balance, amount));
} on InsufficientFunds catch (e) {
return Refused('need ${e.shortBy} more');
} finally {
attempts++;
}
}
String show(WithdrawResult r) => switch (r) {
Done(balance: var b) => 'Done: $b',
Refused(reason: var why) => 'Refused: $why',
};
void main() {
print(show(tryWithdraw(100, 30)));
print(show(tryWithdraw(100, 150)));
try {
tryWithdraw(100, -5);
} on ArgumentError catch (e) {
print('bug caught: ${e.message}');
}
print('attempts: $attempts');
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A sealed class closes the set of subtypes, so a switch expression must cover every case and the compiler catches every un-updated switch when a subtype is added.
- An Exception is a recoverable condition (write custom ones with implements Exception) and an Error is a bug to fix rather than hide.
- In try/on/catch/finally, on selects by type and finally runs even after a return; use rethrow instead of throw e to send a failure onward.
- Choose a sealed type such as Result<T> when failure is an ordinary outcome, and an exception for the unexpected.
Dart class modifiers — Dart