Kinds of errors
| Kind | When it shows | Example |
|---|---|---|
| Syntax (compile-time) error | before the program runs | a missing ;, a wrong type |
| Runtime error (exception) | while it runs | dividing by zero, a bad number format, an index past the end |
| Logic error | never reported | using + where you meant - |
The compiler catches the first kind. Exception handling deals with the second: things that can go wrong at run time even in correct code, such as a user typing letters where a number is expected, or the internet being down.
What happens without handling
void main() {
print('Start');
int n = int.parse('12a');
print(n);
print('End');
}
Running it prints Start, then the exception and a stack trace (the list of function calls that led to it, shortened here):
Start
Unhandled exception:
FormatException: Invalid radix-10 number (at character 1)
12a
^
#0 int._handleFormatError (dart:core-patch/integers_patch.dart:150:5)
...
#4 main (file:///.../crash.dart:3:15)
The program stops at the bad line; End is never printed. In an app, an unhandled exception can close the screen or the whole app.
try and catch
Put the risky code in try. If an exception is thrown, Dart jumps to catch and the program goes on.
void main() {
print('Start');
try {
int n = int.parse('12a');
print(n);
} catch (e) {
print('Not a number: $e');
}
print('End');
}
Start
Not a number: FormatException: Invalid radix-10 number (at character 1)
12a
^
End
catch (e, s) also gives the stack trace s, which shows where the exception came from; log it when debugging.
Catching specific exceptions with on
on Type catches only that kind of exception. Put specific types first and a general catch last.
int safeDivide(String a, String b) {
try {
return int.parse(a) ~/ int.parse(b);
} on FormatException {
print('Please type whole numbers');
} on UnsupportedError catch (e) {
print('Maths problem: ${e.message}');
} catch (e) {
print('Something else went wrong: $e');
}
return 0;
}
void main() {
print(safeDivide('10', '3'));
print(safeDivide('ten', '3'));
print(safeDivide('10', '0'));
}
3
Please type whole numbers
0
Maths problem: Division resulted in non-finite value
0
Integer division by zero (~/ 0) throws an UnsupportedError. Plain / does not throw: 10 / 0 is Infinity.
finally
A finally block runs whether or not an exception happened. Use it to clean up: close a file, hide a loading spinner.
void main() {
for (var input in ['5', 'x']) {
try {
print('Square: ${int.parse(input) * int.parse(input)}');
} on FormatException {
print('Bad input: $input');
} finally {
print('Checked $input');
}
}
}
Square: 25
Checked 5
Bad input: x
Checked x
throw and custom exceptions
throw raises an exception yourself when something is invalid. For your own kinds of problem, write a class that implements Exception.
class InsufficientBalance implements Exception {
final double needed;
InsufficientBalance(this.needed);
@override
String toString() => 'InsufficientBalance: need Rs $needed more';
}
class Wallet {
double balance;
Wallet(this.balance);
void pay(double amount) {
if (amount <= 0) {
throw ArgumentError.value(amount, 'amount', 'must be positive');
}
if (amount > balance) {
throw InsufficientBalance(amount - balance);
}
balance -= amount;
}
}
void main() {
var w = Wallet(500);
for (var amt in [200.0, 450.0, -5.0]) {
try {
w.pay(amt);
print('Paid $amt, left ${w.balance}');
} on InsufficientBalance catch (e) {
print(e);
} on ArgumentError catch (e) {
print('Invalid: ${e.message}');
}
}
}
Paid 200.0, left 300.0
InsufficientBalance: need Rs 150.0 more
Invalid: must be positive
Dart separates Exceptions (problems a program should expect and handle, such as bad input or a network failure) from Errors (bugs in the code, such as RangeError or ArgumentError). Catch exceptions; fix errors.
rethrow
rethrow passes the exception on after doing something with it, such as logging:
int parseAge(String s) {
try {
return int.parse(s);
} on FormatException {
print('log: bad age "$s"');
rethrow;
}
}
void main() {
try {
parseAge('abc');
} on FormatException {
print('Shown to user: please enter your age in numbers');
}
}
log: bad age "abc"
Shown to user: please enter your age in numbers
assert
assert(condition, 'message') checks something that must be true while you develop. Asserts run in debug mode (dart run --enable-asserts, and Flutter debug builds) and are removed from release builds, so never use them to check user input.
double percent(int got, int total) {
assert(total > 0, 'total must be positive');
return got * 100 / total;
}
Failing safely
- Validate input early and give a clear message.
- Catch exceptions where you can do something useful: retry, show a message, use a default.
- Do not catch everything and ignore it: an empty
catch (e) {}hides bugs. - Prefer
int.tryParse(returnsnull) overint.parseplustryfor simple input checks.
Common mistakes
- An empty
catchblock that swallows the problem silently. - A general
catchbefore a specificon: the specific one is never reached. - Throwing plain strings (
throw 'error';): allowed, but you lose a type to catch withon. - Using
assertfor checks that must happen in the released app. - Catching
Errors such asRangeErrorinstead of fixing the bug that causes them.
Key points
- Runtime problems throw exceptions; unhandled ones stop the program.
tryholds risky code;catchhandles it;on Typehandles one kind;finallyalways runs.throwraises an exception; custom exceptions implementException.rethrowpasses an exception on after handling part of it.assertchecks assumptions during development only.
Practice questions
1. Write code that reads '45' and '4x' with int.parse and prints Invalid for the bad one without crashing.
void main() {
for (var s in ['45', '4x']) {
try {
print(int.parse(s));
} on FormatException {
print('Invalid');
}
}
}2. When does a finally block run?
Always: after the try block finishes normally, and also after a catch handles an exception, and even when the exception is not caught.
3. Create an exception AgeTooLow and throw it when an age below 18 is passed to register(int age).
class AgeTooLow implements Exception {}
void register(int age) {
if (age < 18) throw AgeTooLow();
print('Registered');
}
void main() {
try {
register(15);
} on AgeTooLow {
print('Must be 18 or older');
}
}4. What is the difference between 10 / 0 and 10 ~/ 0 in Dart?
10 / 0 gives the double Infinity without an exception. 10 ~/ 0 throws an UnsupportedError.
5. Why should assert not be used to check a user's password length?
Asserts are removed from release builds, so the check would not run for real users. Use an if and throw or show a message.