throw
- Dart course
- Beginner
- Lesson 101/116
- 4 min
Learn to throw exceptions with throw.
throw
To throw your own error use throw. You can throw an Exception object or a string. For example throw Exception("negative number");. This is used to stop the program and warn the caller when a condition is not met.
The thrown value propagates up the call chain until a catch is found. If none is found the program ends. Typical use: validate a function parameter, throw if invalid. This lets the caller know and fix the issue. Throw is an expression, so it can be used in functions that return a value.
Conditional throw
Throw is most often used with an if. When the condition fails an error is thrown. For example an age check: if (age < 0) throw ArgumentError("age negative");. This is a guard at the start of a function.
Throw is an expression that returns a value; so it works with the ternary operator too. final result = cond ? value : throw Exception("Invalid");. This also works in a switch expression; _ => throw Exception("unknown"). Throw being an expression got stronger with Dart 3; it can now appear wherever a value is expected.
Practice Your turn: validate a negative age
In main assign final age = -5;. Use an if to throw an ArgumentError when age < 0. Wrap the call in a try block and print the error with catch (e).
Starter code
void main() {
// final age = -5;
// try with an if that throws ArgumentError when negative
// handle the error and print
}Sample solution
void main() {
try {
final age = -5;
if (age < 0) throw ArgumentError("age negative");
} catch (e) {
print(e);
}
}Expected output
Invalid argument(s): age negative
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The throw call
if (number < 0) {
____ Exception("negative number");
}
if (number < 0) {
throw Exception("negative number");
}
Explanation: Write throw; followed by the object to throw.
2 What do you do when a condition is not met?
if (age < 0) {
____ ArgumentError("age negative");
}- throw
- return Correct answer
- break
- continue
Explanation: throw raises; return gives a value, break exits a loop, continue skips a loop.
3 Match throw
| Term | Meaning |
|---|---|
throw |
raises an error |
Exception |
general error class |
ArgumentError |
invalid parameter |
if |
tests a condition |