on clause
- Dart course
- Beginner
- Lesson 104/116
- 5 min
Learn to catch specific exception types with on.
The on clause
catch catches every error. Sometimes you want only a specific type. For that you use on. on FormatException catch (e) { ... } catches only a FormatException; others propagate up.
Typical use: try { int.parse(input); } on FormatException { print("not a number"); } on Exception catch (e) { print("other error: $e"); }. Each on catches a different type and gives a different message. on can be used without catch (e); then you cannot access the object. With on you pick the type, with catch (e) you get the object.
Practice Your turn: catch by type
Inside try call int.parse on a non-numeric string. Use on FormatException to print "not a number". Then use on Exception catch (e) to print e for general errors. Different types give different messages.
Starter code
void main() {
// try parsing a non-numeric string
// for parse errors print "not a number"
// for general errors print the error
}Sample solution
void main() {
try {
int.parse("apple");
} on FormatException {
print("not a number");
} on Exception catch (e) {
print(e);
}
}Expected output
not a number
on vs catch
on FormatException catches only FormatException. catch (e) catches everything. You can combine them: on FormatException catch (e). You pick the type and get the object as e. Writing only on FormatException gives no access to the object.
Multiple on clauses can be written side by side; they are tried in order. The first match runs. The order on FormatException { ... } on Exception { ... } matters; since FormatException is an Exception, the more specific one must come first. A finally block can also be added at the end.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 on FormatException
try {
int.parse("apple");
} ____ FormatException {
print("not a number");
}
try {
int.parse("apple");
} on FormatException {
print("not a number");
}
Explanation: on catches a specific type.
2 What happens when multiple on clauses are written together?
try {
process();
} on FormatException {
...
} on Exception {
...
}- The first match runs Correct answer
- Every block runs
- Only the last runs
- It throws
Explanation: The first matching on block runs.
3 Match on/catch
| Term | Meaning |
|---|---|
on FormatException |
only this type |
catch (e) |
all types |
on ... catch (e) |
type + object |
finally |
always |