Assertions
suggest changeAn assertion states something you believe is always true at a given point in the program. If it turns out to be false, there is a bug, and the program stops right away with an AssertionError instead of carrying on with bad data.
Dart has a built-in assert statement:
assert(condition);
assert(condition, message);
The thing to remember about Dart assertions: they only run when assertions are enabled. By default they are off in dart run and in compiled executables, and on in dart test, Flutter debug builds and IDE debug sessions. That one fact decides what assertions are good for: catching programmer errors during development and testing, never validating input in production.
The examples below were run with Dart 3.13. In error messages, the long absolute path of the project has been shortened to file:///C:/app.
A first assertion
int average(List<int> values) {
assert(values.isNotEmpty, 'average() needs at least one value');
var sum = 0;
for (final v in values) {
sum += v;
}
return sum ~/ values.length;
}
void main() {
print(average([2, 4, 9]));
print(average([]));
}
With a plain dart run, the assertion is skipped and the program fails later, with a less helpful error:
$ dart run bin/a1.dart
5
Unhandled exception:
IntegerDivisionByZeroException
#0 int.~/ (dart:core-patch/integers.dart:27:7)
#1 average (file:///C:/app/bin/a1.dart:7:14)
#2 main (file:///C:/app/bin/a1.dart:12:9)
With --enable-asserts the program stops at the broken assumption, and the error says exactly what was expected:
$ dart run --enable-asserts bin/a1.dart
5
Unhandled exception:
'file:///C:/app/bin/a1.dart': Failed assertion: line 2 pos 10: 'values.isNotEmpty': average() needs at least one value
#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:67:4)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:49:5)
#2 average (file:///C:/app/bin/a1.dart:2:10)
#3 main (file:///C:/app/bin/a1.dart:12:9)
The message contains the file, line and column, the source text of the condition and your message. In a bigger program, getting the error at the cause rather than at a symptom three functions away can save a lot of debugging time.
The condition must have the static type bool. Something like assert(values.length) is a compile error, and so is passing a function (older Dart versions accepted assert(() => ...), Dart 2 and later do not).
Enabling assertions
| How you run the code | Assertions |
|---|---|
dart run file.dart, dart file.dart |
off |
dart run --enable-asserts file.dart |
on |
dart test |
on |
| VS Code / IntelliJ debug session | on |
dart compile exe / aot-snapshot |
off (compiled out) |
dart compile exe --enable-asserts |
on |
dart compile js |
off, unless --enable-asserts |
| Flutter debug build | on |
| Flutter profile and release builds | off |
The flag works for the VM directly too: dart --enable-asserts bin/main.dart.
When assertions are compiled into an AOT executable with dart compile exe --enable-asserts, the check works, but the error message shows 'null' instead of the source of the condition, because the source text isn't kept in the binary:
$ dart compile exe --enable-asserts bin/b1.dart -o b1.exe
$ ./b1.exe
half: 50
Unhandled exception:
'file:///c:/app/bin/b1.dart': Failed assertion: line 10 pos 16: 'null': start (10) must be <= end (3)
That is one more reason to always give assertions a message.
To find out at runtime whether assertions are on, use an assignment inside an assert: it only runs when they are enabled. See "Debug-only code and build modes" in Debugging for this trick and for bool.fromEnvironment('dart.vm.product').
AssertionError and the message
A failed assertion throws an AssertionError. It is an Error, not an Exception, which in Dart means "a bug in the program" rather than "a failure the program is expected to handle":
void main() {
try {
assert(1 + 1 == 3, 'math is broken');
} on AssertionError catch (e) {
print('type: ${e.runtimeType}');
print('message: ${e.message}');
print('is Error: ${e is Error}, is Exception: ${e is Exception}');
print('toString: $e');
}
try {
assert(false);
} on AssertionError catch (e) {
print('no message: ${e.message}');
}
try {
assert(false, {'code': 42, 'reason': 'not a string'});
} on AssertionError catch (e) {
print('object message: ${e.message} (${e.message.runtimeType})');
}
}
Output with --enable-asserts:
type: _AssertionError
message: math is broken
is Error: true, is Exception: false
toString: 'file:///C:/app/bin/a2.dart': Failed assertion: line 3 pos 12: '1 + 1 == 3': math is broken
no message: null
object message: {code: 42, reason: not a string} (_Map<String, Object>)
Without the flag, the same program prints nothing at all: no assertion fails, so no catch block runs.
messageisObject?. It is usually a string, but any object is allowed and is converted withtoString()in the error text.toString()includes the location and the condition source;messageholds only what you passed.- Catching
AssertionErroris fine in tests and in test harnesses, but not in application code. A failed assertion means the program is in a state you didn't plan for; the right fix is to fix the code, not to recover.
Assertions are free when disabled
When assertions are off, neither the condition nor the message is evaluated. When they are on, the message is evaluated only if the condition is false:
int calls = 0;
bool expensiveCheck() {
calls++;
print(' running expensiveCheck');
return true;
}
String describe() {
print(' building message');
return 'details';
}
void main() {
assert(expensiveCheck(), describe());
print('expensiveCheck called $calls time(s)');
final items = [1, 2, 3];
assert(items.remove(3)); // BAD: side effect inside assert
print('items: $items');
}
$ dart run bin/a3.dart
expensiveCheck called 0 time(s)
items: [1, 2, 3]
$ dart run --enable-asserts bin/a3.dart
running expensiveCheck
expensiveCheck called 1 time(s)
items: [1, 2]
Two consequences:
- You can afford slow checks (walking a whole data structure, recomputing a value from scratch) because they cost nothing in production. Interpolated messages like
'got $value'are also free. - Never put side effects inside an assertion. The
items.remove(3)above changes the list only when assertions are on, so the program behaves differently in tests and in production. This kind of bug is very hard to find, because it disappears as soon as you run the code under a debugger.
Assertions in constructors
An initializer list can contain assertions. This is the standard way to check constructor arguments, and the only way for const constructors, which can't have a body:
class Percent {
final int value;
const Percent(this.value)
: assert(value >= 0 && value <= 100, 'percent out of range: $value');
}
class Range {
final int start, end;
Range(this.start, this.end)
: assert(start <= end, 'start ($start) must be <= end ($end)');
int get length => end - start;
}
void main() {
const half = Percent(50);
print('half: ${half.value}');
final r = Range(10, 3);
print('length: ${r.length}');
}
$ dart run bin/b1.dart
half: 50
length: -7
$ dart run --enable-asserts bin/b1.dart
half: 50
Unhandled exception:
'file:///C:/app/bin/b1.dart': Failed assertion: line 10 pos 16: 'start <= end': start (10) must be <= end (3)
#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:67:4)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:49:5)
#2 new Range (file:///C:/app/bin/b1.dart:10:16)
#3 main (file:///C:/app/bin/b1.dart:19:13)
Initializer-list assertions run before the constructor body and before the superclass constructor, so the object is never observed in a half-built, invalid state. You can have several of them, separated by commas, mixed with field initializers.
Const constructors are checked at compile time
When a const constructor is used in a constant expression, its assertions are evaluated by the compiler, whether or not assertions are enabled at runtime:
class Percent {
final int value;
const Percent(this.value)
: assert(value >= 0 && value <= 100, 'percent out of range');
}
const tooMuch = Percent(150);
void main() {
print(tooMuch.value);
}
$ dart run bin/b2.dart
bin/b2.dart:7:17: Error: Constant evaluation error:
const tooMuch = Percent(150);
^
bin/b2.dart:4:27: Context: This assertion failed with message: percent out of range
: assert(value >= 0 && value <= 100, 'percent out of range');
^
bin/b2.dart:7:7: Context: While analyzing:
const tooMuch = Percent(150);
$ dart analyze bin/b2.dart
error - b2.dart:7:17 - Evaluation of this constant expression throws an exception. - const_eval_throws_exception
- The exception is 'An assertion failed with message 'percent out of range'.' and occurs here at b2.dart:4:9.
This makes assertions in const constructors a cheap way to validate configuration tables and other constant data: a bad value is reported by the analyzer in the editor, long before anything runs. Calling the same constructor without const (Percent(150)) is an ordinary runtime check, subject to --enable-asserts. See Constants for more on constant expressions.
Checking invariants
A class invariant is a property that must hold after every public operation. A private method that checks all of them, called from an assert, catches corruption right after the operation that caused it:
class Inventory {
final Map<String, int> _stock = {};
int _total = 0;
void add(String item, int count) {
_stock[item] = (_stock[item] ?? 0) + count;
_total += count;
assert(_checkInvariants());
}
void remove(String item, int count) {
final have = _stock[item] ?? 0;
_stock[item] = have - count;
_total -= count;
assert(_checkInvariants());
}
bool _checkInvariants() {
final sum = _stock.values.fold(0, (a, b) => a + b);
assert(sum == _total, 'total is $_total but items sum to $sum');
for (final MapEntry(:key, :value) in _stock.entries) {
assert(value >= 0, 'negative stock for $key: $value');
}
return true;
}
}
void main() {
final inv = Inventory()
..add('apple', 3)
..add('pear', 2);
print('added');
inv.remove('apple', 5);
print('removed');
}
$ dart run bin/c2.dart
added
removed
$ dart run --enable-asserts bin/c2.dart
added
Unhandled exception:
'file:///C:/app/bin/c2.dart': Failed assertion: line 22 pos 14: 'value >= 0': negative stock for apple: -2
The checker returns true so it can be used as an assertion condition, and uses its own assertions inside so that each problem gets a specific message. Since the whole call is inside assert, the fold over all items costs nothing in production.
The same idea works for postconditions, checking a function's result before returning it:
({int w, int h}) parseSize(String s) {
final parts = s.split('x');
if (parts.length != 2) throw FormatException('expected WxH', s);
final w = int.parse(parts[0]), h = int.parse(parts[1]);
final size = (w: w, h: w); // BUG: should be h
assert(size.h == h, 'parseSize mixed up width and height');
return size;
}
Debug-only blocks with a closure
assert takes an expression, but sometimes you want a few statements: a loop, some logging. Wrap them in a closure that you call immediately and that returns true:
List<int> mergeSorted(List<int> a, List<int> b) {
final out = <int>[];
var i = 0, j = 0;
while (i < a.length && j < b.length) {
out.add(a[i] <= b[j] ? a[i++] : b[j++]);
}
out
..addAll(a.skip(i))
..addAll(b.skip(j));
assert(() {
// debug-only block: any statements are allowed here
for (var k = 1; k < out.length; k++) {
if (out[k - 1] > out[k]) {
print('not sorted at index $k: $out');
return false;
}
}
print('[debug] merged ${a.length} + ${b.length} -> ${out.length}, sorted');
return true;
}());
return out;
}
void main() {
print(mergeSorted([1, 4, 9], [2, 3, 10]));
print(mergeSorted([5, 1], [2]));
}
$ dart run bin/c3.dart
[1, 2, 3, 4, 9, 10]
[2, 5, 1]
$ dart run --enable-asserts bin/c3.dart
[debug] merged 3 + 3 -> 6, sorted
[1, 2, 3, 4, 9, 10]
not sorted at index 2: [2, 5, 1]
Unhandled exception:
'file:///C:/app/bin/c3.dart': Failed assertion: line 11 pos 10: '() {
// debug-only block: any statements are allowed here
...
Note the trailing (): assert(() { ... }()) calls the closure. Forgetting it is a compile error, because a function is not a bool. Flutter uses this pattern a lot for debug-only checks and diagnostics. The failure message includes the whole closure source, so for long blocks print a clear message before returning false, as above.
Assertions don't promote types
Flow analysis does not use assertions for type promotion. After assert(x != null), x is still nullable:
String? lookup(String key) => key == 'name' ? 'Dart' : null;
void main() {
final name = lookup('name');
assert(name != null);
print(name.length);
}
$ dart analyze bin/c1.dart
error - c1.dart:6:14 - The property 'length' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!'). - unchecked_use_of_nullable_value
That's by design: the assertion may not run, so it proves nothing. Use a check that always runs instead: name! (throws a TypeError if null), or if (name == null) throw StateError('...'), after which name is promoted to String. See Null safety.
Assertions vs. argument checks
Because assertions can be turned off, they are the wrong tool for anything that must be checked in production:
- Use
assertfor internal assumptions: private helpers, invariants, results of your own algorithms, things that can only go wrong if the code itself is wrong. - Throw an error for invalid arguments to public APIs, and an exception for invalid input from users, files and the network.
dart:core has static helpers that make argument checks one-liners:
class Account {
int _balance = 0;
int get balance => _balance;
// Public API: validate arguments always, in every build mode.
void withdraw(int amount) {
RangeError.checkValueInInterval(amount, 1, _balance, 'amount');
_applyWithdrawal(amount);
}
void deposit(int amount) {
if (amount <= 0) {
throw ArgumentError.value(amount, 'amount', 'must be positive');
}
_balance += amount;
}
// Private helper: callers have already validated, so assert is enough.
void _applyWithdrawal(int amount) {
assert(amount > 0 && amount <= _balance);
_balance -= amount;
}
}
void main() {
final acc = Account()..deposit(100);
for (final amount in [30, 0, 500]) {
try {
acc.withdraw(amount);
print('withdrew $amount, balance ${acc.balance}');
} on RangeError catch (e) {
print(e);
}
}
try {
acc.deposit(-10);
} on ArgumentError catch (e) {
print(e);
}
final items = ['a', 'b', 'c'];
try {
IndexError.check(5, items.length, indexable: items, name: 'index');
} on IndexError catch (e) {
print(e);
}
try {
RangeError.checkNotNegative(-1, 'count');
} on RangeError catch (e) {
print(e);
}
final String? token = null;
try {
ArgumentError.checkNotNull(token, 'token');
} on ArgumentError catch (e) {
print(e);
}
}
Output (the same with or without --enable-asserts):
withdrew 30, balance 70
RangeError (amount): Invalid value: Not in inclusive range 1..70: 0
RangeError (amount): Invalid value: Not in inclusive range 1..70: 500
Invalid argument (amount): must be positive: -10
RangeError (index): Index out of range: index should be less than 3: 5
RangeError (count): Invalid value: Not greater than or equal to 0: -1
Invalid argument(s) (token): Must not be null
| Helper | Throws when |
|---|---|
ArgumentError.checkNotNull(v, name) |
v is null (returns v as non-nullable) |
ArgumentError.value(v, name, msg) |
constructor, you throw it yourself |
RangeError.checkNotNegative(v, name) |
v < 0 |
RangeError.checkValueInInterval(v, min, max, name) |
v outside min..max |
RangeError.checkValidRange(start, end, length) |
not 0 <= start <= end <= length |
IndexError.check(i, length) |
i not in 0..length-1 |
StateError(msg) |
constructor, for "object is in the wrong state" |
For parse failures and bad external data, throw a FormatException or your own exception type (see Exceptions and Custom exception).
Don't swallow assertion failures
A bare catch catches everything, AssertionError included. That can silently hide the very bug the assertion was meant to expose. Using parseSize from the postcondition example above:
void main() {
// Too broad: also catches the AssertionError and hides the bug.
try {
print(parseSize('640x480'));
} catch (e) {
print('bad input, using default');
}
// Better: catch only the failures you expect.
try {
print(parseSize('640x480'));
} on FormatException catch (e) {
print('bad input: ${e.message}');
}
}
$ dart run --enable-asserts bin/e1.dart
bad input, using default
Unhandled exception:
'file:///C:/app/bin/e1.dart': Failed assertion: line 6 pos 10: 'size.h == h': parseSize mixed up width and height
The first block reports the bug as "bad input", which is wrong and misleading. The second lets the assertion reach the top level, where it can't be missed. Catch specific types with on, and if you must catch everything (for example at the top of a request handler), at least log the error and stack trace.
Testing assertions
dart test runs with assertions enabled, so tests exercise all your assertions automatically. You can also test that an assertion fires, with throwsA and isA<AssertionError>():
// lib/range.dart
class Range {
final int start, end;
Range(this.start, this.end)
: assert(start <= end, 'start ($start) must be <= end ($end)');
int get length => end - start;
}
// test/range_test.dart
import 'package:asrt/range.dart';
import 'package:test/test.dart';
void main() {
test('length of a valid range', () {
expect(Range(3, 10).length, 7);
});
test('start after end fails the assertion', () {
expect(
() => Range(10, 3),
throwsA(
isA<AssertionError>().having(
(e) => e.message,
'message',
contains('must be <= end'),
),
),
);
});
}
$ dart test
00:00 +0: test\range_test.dart: length of a valid range
00:00 +1: test\range_test.dart: start after end fails the assertion
00:00 +2: All tests passed!
Such a test passes only when assertions are on. That's the default for dart test, but keep it in mind if you ever run the test file some other way. Flutter's flutter_test has a ready-made throwsAssertionError matcher. See Parameterized tests and Testing in CI for more on testing.
Summary
assert(condition, [message])throws anAssertionErrorwhen the condition is false and assertions are enabled.- Assertions are off in
dart runand compiled executables, and on indart test, IDE debug sessions and Flutter debug builds. Turn them on with--enable-asserts. - When off, neither the condition nor the message is evaluated: expensive checks are free, and side effects inside
assertare a bug. - Use initializer-list assertions to check constructor arguments; in
constconstructors used in constant expressions they are checked at compile time. - Check invariants and postconditions with a
bool-returning helper insideassert, and useassert(() { ...; return true; }())for debug-only blocks. - Assertions don't promote types; use
!or an explicitthrowwhen you need a guarantee. - Use
assertfor programmer errors only. Validate public API arguments withArgumentError/RangeErrorhelpers and external input with exceptions. - Avoid bare
catchblocks that swallowAssertionError, and test assertions withthrowsA(isA<AssertionError>()).