The Exception class
- Dart course
- Beginner
- Lesson 103/116
- 5 min
Learn the Exception class and custom exceptions.
The Exception class
In Dart all exceptions implement the Exception interface. You can write your own exception class; this lets you name the special case clearly. class BalanceError implements Exception { final String message; BalanceError(this.message); String toString() => message; }
You throw it with throw BalanceError("insufficient balance"). In a catch block you can match by type: catch (e) { if (e is BalanceError) ... }. Your own exception class carries the reason explicitly; the caller can act on it. Overriding toString makes print(e) output meaningful.
Overriding toString
When you override toString in an exception class, print(e) shows the text you want. The default toString prints the class name and a complex identifier, making logs unreadable.
Example: String toString() => "BalanceError: $message";. So print(e) outputs BalanceError: insufficient balance. Very useful when debugging. The final String message field carries the reason; in a catch block you access e.message after checking the type with is.
Practice Your turn: a custom exception class
Define a class BalanceError that implements Exception. Add final String message and a BalanceError(this.message) constructor. The toString method returns message. In main throw BalanceError("insufficient balance") and print it with catch (e).
Starter code
void main() {
// Define the BalanceError class
// try throws BalanceError
// handle the error and print
}Sample solution
class BalanceError implements Exception {
final String message;
BalanceError(this.message);
String toString() => message;
}
void main() {
try {
throw BalanceError("insufficient balance");
} catch (e) {
print(e);
}
}Expected output
insufficient balance
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match Exception
| Term | Meaning |
|---|---|
Exception |
the general interface |
implements |
binds the class |
toString |
gives the text |
final String |
immutable message |
2 Which interface does our exception class implement?
class BalanceError ____ Exception {
final String message;
BalanceError(this.message);
}- implements
- extends
- with
- abstract Correct answer
Explanation: implements Exception applies the interface.
3 toString override
String ____() => message;
String toString() => message;
Explanation: toString gives the text representation.