On this page11 sections
Lecture 038: Assignment: A Custom Exception Class
| Day | 13: Exception Handling |
| Lecture | 038 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
StateError('Insufficient balance')works, but it doesn't say how much was missing, and code can't tell it apart from any otherStateError. Your own exception class can carry exactly the details your app needs, and be caught by name. This lecture ends with an assignment.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Assignment · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 030–035 (classes, constructors, getters) and 037 (exception handling).
Learning Objectives
- Create an exception class that
implements Exception - Give it fields that describe the problem
- Override
toString()so it prints a useful message - Throw it, and catch it by name with
on
1. Why Your Own Exception?
| Built-in error | Your own exception |
|---|---|
StateError('Insufficient balance') | InsufficientBalanceException(balance, requested) |
| only a message | real fields: balance, requested, shortBy |
caught as one of many StateErrors | caught exactly: on InsufficientBalanceException |
2. Writing One
An exception is an ordinary class that implements Exception (the interface Dart uses for errors
that are meant to be caught):
class InsufficientBalanceException implements Exception {
final double balance;
final double requested;
InsufficientBalanceException(this.balance, this.requested);
double get shortBy => requested - balance;
@override
String toString() =>
'InsufficientBalanceException: requested Rs $requested, balance Rs $balance (short by Rs $shortBy)';
}
class InvalidAmountException implements Exception {
final String message;
InvalidAmountException(this.message);
@override
String toString() => 'InvalidAmountException: $message';
}- Fields carry the details.
toString()decides whatprint(e)shows. Without it, you'd only seeInstance of 'InsufficientBalanceException'.
3. Throwing and Catching It
class Account {
final String owner;
double balance;
Account(this.owner, this.balance);
void withdraw(double amount) {
if (amount <= 0) {
throw InvalidAmountException('amount must be more than zero, got $amount');
}
if (amount > balance) {
throw InsufficientBalanceException(balance, amount);
}
balance -= amount;
print('$owner withdrew Rs $amount, balance Rs $balance');
}
}The caller catches each type by name and can read its fields:
try {
acc.withdraw(amount);
} on InsufficientBalanceException catch (e) {
print('Declined: you need Rs ${e.shortBy} more');
} on InvalidAmountException catch (e) {
print('Declined: ${e.message}');
}Code Examples
Example 1: A Bank Account With Custom Exceptions
// (the two exception classes and Account from above)
void main() {
var acc = Account('Sara', 3000);
for (var amount in [1000.0, 0.0, 5000.0, 2000.0]) {
try {
acc.withdraw(amount);
} on InsufficientBalanceException catch (e) {
print('Declined: you need Rs ${e.shortBy} more');
} on InvalidAmountException catch (e) {
print('Declined: ${e.message}');
}
}
try {
acc.withdraw(10000);
} catch (e) {
print(e);
}
}Output
Sara withdrew Rs 1000.0, balance Rs 2000.0
Declined: amount must be more than zero, got 0.0
Declined: you need Rs 3000.0 more
Sara withdrew Rs 2000.0, balance Rs 0.0
InsufficientBalanceException: requested Rs 10000.0, balance Rs 0.0 (short by Rs 10000.0)The last print(e) uses the overridden toString(), a clear message ready for a log.
Common Beginner Mistakes
1. Forgetting to override toString()
class NoToString implements Exception {
final String message;
NoToString(this.message);
}
try {
throw NoToString('Oops');
} catch (e) {
print(e);
}Output
Instance of 'NoToString'The message is lost in the output. Override toString().
2. Throwing the class instead of an object
class AgeException implements Exception {}
throw AgeException;Unhandled exception:
AgeExceptionIt looks almost right, but this throws the type itself, not an exception object, so
on AgeException won't catch it. Write throw AgeException(); with brackets.
3. Not implementing Exception: Dart can throw any object, so class MyError {} can be
thrown, but on Exception won't catch it, and it doesn't signal "this is an error to handle".
Always write implements Exception.
Assignment
Build a student registration system with your own exceptions.
- Create
InvalidAgeException implements Exceptionwith a fieldint ageand atoString()that says the age and the allowed range (5–100). - Create
DuplicateStudentException implements Exceptionwith a fieldString name. - Create a class
Schoolwith aList<String> studentsfield and a methodvoid register(String name, int age)that:- throws
InvalidAgeExceptionifage < 5orage > 100, - throws
DuplicateStudentExceptionifnameis already in the list, - otherwise adds the name and prints
Registered <name>.
- throws
- In
main, try to register:('Ali', 12),('Sara', 3),('Ali', 14),('Zara', 9). Catch each exception type separately and print a friendly message.
Expected output (your wording may differ):
Registered Ali
Cannot register Sara: age 3 is outside 5–100
Cannot register Ali: already registered
Registered ZaraPractice Questions
- What must a class do to be a proper Dart exception?
- Why override
toString()in an exception class? - What's the difference between
throw MyException;andthrow MyException();? - How do you read an exception's field in a
catch? - Give one advantage of a custom exception over
StateError('...').
Practice Answers
implements Exception.- So
print(e)shows a useful message instead ofInstance of '...'. - The first throws the type itself; the second throws an exception object, which is the correct way.
- Use
on MyException catch (e), thene.fieldName. - It can carry specific fields (like
shortBy) and be caught by its exact name.
Key Takeaways
- A custom exception is a class that
implements Exception. - Give it fields describing the problem, and override
toString(). throw MyException(...), with brackets, to create the object.- Catch it precisely with
on MyException catch (e)and use its fields.