try/catch
- Dart course
- Beginner
- Lesson 100/116
- 5 min
Learn to catch errors with try/catch.
try/catch
An operation can throw an error; for example int.parse throws a FormatException when given a non-numeric string. To catch it you put the risky code inside a try block and the recovery code inside a catch block.
Example: try { final n = int.parse("apple"); } catch (e) { print("not a number: $e"); }. When an error occurs the program does not stop; the catch block runs and the program continues. The e variable carries the thrown object. This lets you show a friendly error message to the user.
The catch parameter
Inside catch (e) the variable e carries the thrown object. It is usually an Exception or an Error. You can get its text with e.toString(); print(e) does the same.
If you also want the stack trace you add a second parameter: catch (e, s). Here s is a StackTrace that shows where the error came from. Very useful when debugging. You can also write catch with no parameter: catch { ... }; then you cannot access the object but you still catch the error.
Practice Your turn: catch a parse error
Inside a try block call int.parse on a non-numeric string. In a catch (e) block print "not a number". The program shows a friendly message instead of crashing.
Starter code
void main() {
// Try parsing a string in a try block
// Print "not a number" on error
}Sample solution
void main() {
try {
int.parse("apple");
} catch (e) {
print("not a number");
}
}Expected output
not a number
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does int.parse("apple") throw?
try {
int.parse("apple");
} catch (e) {
print(e);
}- FormatException Correct answer
- TypeError
- RangeError
- It does not throw
Explanation: int.parse throws a FormatException on a non-numeric string.
2 The catch block
try {
int.parse("apple");
} ____ (e) {
print("not a number");
}
try {
int.parse("apple");
} catch (e) {
print("not a number");
}
Explanation: The catch block catches the error.
3 Match try/catch
| Term | Meaning |
|---|---|
try |
holds risky code |
catch |
catches the error |
e |
the thrown object |
FormatException |
int.parse error |