On this page12 sections
Lecture 037: Exception Handling
| Day | 13: Exception Handling |
| Lecture | 037 of 057 |
| Estimated video length | 14 min |
| Target | Dart 3.12 |
| Level | Beginner |
A user types "abc" where a number belongs. A file is missing. The internet drops. Things go wrong while a program runs, and without a plan, the program crashes. Exception handling catches the problem, deals with it, and lets the program carry on.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 009 (int.parse), 011 (lists), 020 (loops) and 025 (functions).
Learning Objectives
- Explain what an exception is
- Catch exceptions with
try/catch - Catch specific types with
on - Run clean-up code with
finally - Raise your own errors with
throw
1. What Is an Exception?
An exception is an error that happens while the program is running. If nothing handles it, the program stops:
void main() {
print('Start');
var n = int.parse('12a');
print('End $n');
}Start
Unhandled exception:
FormatException: Invalid radix-10 number (at character 1)
12a
^End never prints.
2. try / catch
Put risky code in try. If it throws, Dart jumps straight to catch, and the program continues
afterwards:
try {
var n = int.parse('12a');
print('Parsed $n'); // skipped, because the line above threw
} catch (e) {
print('Could not read the number: $e');
}
print('Program keeps going');Output
Could not read the number: FormatException: Invalid radix-10 number (at character 1)
12a
^
Program keeps goinge holds the exception object, so you can print it or inspect it.
3. on: Catch a Specific Type
Different problems throw different types. on Type catches only that type:
try {
var list = [1, 2, 3];
print(list[5]);
} on RangeError {
print('That position does not exist');
}Combine on and catch to get the object too:
try {
print(10 ~/ 0);
} on UnsupportedError catch (e) {
print('Maths problem: $e'); // Maths problem: IntegerDivisionByZeroException
}| Common type | Thrown when… |
|---|---|
FormatException | text can't be parsed (int.parse('abc')) |
RangeError | an index is out of range (list[10]) |
UnsupportedError | an operation isn't allowed (5 ~/ 0, adding to a const list) |
StateError | something is in the wrong state (firstWhere with no match) |
ArgumentError | a function got a bad argument |
4. Several Handlers, and finally
List specific on clauses first and a general catch last. finally runs every time,
whether there was an error or not:
for (var input in ['42', 'abc']) {
try {
var value = int.parse(input);
print('Got $value');
} on FormatException catch (e) {
print('Format problem: ${e.message}');
} catch (e) {
print('Something else went wrong: $e');
} finally {
print('Finished with "$input"');
}
}Output
Got 42
Finished with "42"
Format problem: Invalid radix-10 number
Finished with "abc"finally is the place for clean-up that must always happen: closing a file, hiding a loading
spinner.
5. throw: Raise Your Own Error
When your function gets something it can't work with, throw an exception:
void checkAge(int age) {
if (age < 0) {
throw ArgumentError('Age cannot be negative: $age');
}
print('Age ok');
}
try {
checkAge(-5);
} catch (e) {
print('Caught: $e'); // Caught: Invalid argument(s): Age cannot be negative: -5
}throw stops the function at once, like return, but sends an error instead of a value.
Code Examples
Example 1: Safe Withdrawals
double withdraw(double balance, String input) {
var amount = double.parse(input);
if (amount <= 0) {
throw ArgumentError('Amount must be positive');
}
if (amount > balance) {
throw StateError('Insufficient balance');
}
return balance - amount;
}
void main() {
var balance = 5000.0;
for (var input in ['1500', 'abc', '-20', '9000', '500']) {
try {
balance = withdraw(balance, input);
print('Withdrew $input. Balance: $balance');
} on FormatException {
print('"$input" is not a number');
} on ArgumentError catch (e) {
print('Rejected $input: ${e.message}');
} on StateError catch (e) {
print('Rejected $input: ${e.message}');
} finally {
print('--');
}
}
}Output
Withdrew 1500. Balance: 3500.0
--
"abc" is not a number
--
Rejected -20: Amount must be positive
--
Rejected 9000: Insufficient balance
--
Withdrew 500. Balance: 3000.0
--Each bad input is handled differently, balance only changes when the withdrawal succeeds, and
the loop never crashes.
Common Beginner Mistakes
1. try with nothing after it
try {
var n = int.parse('5');
}Error: A try block must be followed by an 'on', 'catch', or 'finally' clause.2. A general catch before a specific on
try {
int.parse('x');
} catch (e) {
print('error');
} on FormatException {
print('format');
}It prints error, and the on FormatException clause can never run. dart analyze warns:
warning - Dead code: Catch clauses after a 'catch (e)' or an 'on Object catch (e)' are never reached.Put specific on clauses first, and the general catch last.
3. Catching everything and hiding it: catch (e) {} with an empty body makes bugs
invisible. At least print or log the error.
4. Using exceptions for normal checks: if you can check first (int.tryParse,
list.isNotEmpty), that's usually simpler than catching.
Practice Questions
- What happens to the lines after the failing line inside a
try? - What's the difference between
catch (e)andon FormatException? - When does a
finallyblock run? - Write code that tries
int.parse(text)and printsNot a numberif it fails. - Write a function
setQuantity(int q)that throws anArgumentErrorwhenq < 1.
Practice Answers
- They're skipped. Dart jumps to the matching
on/catch. catch (e)catches anything;on FormatExceptioncatches only that type.- Always, whether an exception happened or not.
try {
print(int.parse(text));
} on FormatException {
print('Not a number');
}void setQuantity(int q) {
if (q < 1) {
throw ArgumentError('Quantity must be at least 1');
}
print('Quantity: $q');
}Key Takeaways
- An unhandled exception stops the program.
try { risky } catch (e) { handle }catches it and carries on.on Typecatches one kind of error; put specific ones first.finallyalways runs; use it for clean-up.throwraises an error when your code gets something it can't handle.