Summary - Exceptions
- Dart course
- Beginner
- Lesson 105/116
- 5 min
Combine try/catch, finally and a custom exception to write a bank account class.
Summary - Exceptions
In this group you learned exception handling: catching with try/catch, throwing with throw, cleanup with finally, custom exceptions with the Exception class and type-based catching with on. Now we combine them all in a bank account class.
A bank account checks the balance when withdrawing. If insufficient, it throws a BalanceError. The caller wraps with try, gives a custom message with on BalanceError, and writes a log entry with finally. This shows how exceptions are used in a real application.
Practice Your turn: balance check
Define a class BankAccount. Add int balance and a BankAccount(this.balance) constructor. The method void withdraw(int amount) throws Exception("insufficient balance") when balance < amount. In main init with final a = BankAccount(100);, call a.withdraw(150) inside try and print with catch (e).
Starter code
void main() {
// Define the BankAccount class
// try calls withdraw
// handle the error and print
}Sample solution
class BankAccount {
int balance;
BankAccount(this.balance);
void withdraw(int amount) {
if (balance < amount) throw Exception("insufficient balance");
}
}
void main() {
final a = BankAccount(100);
try {
a.withdraw(150);
} catch (e) {
print(e);
}
}Expected output
Exception: insufficient balance
Practice Your turn: bank with a custom exception
Define a class BalanceError implementing Exception; final String message field and toString returns message. In the BankAccount class withdraw(int amount) throws BalanceError("insufficient balance") when balance is insufficient. In main wrap a.withdraw(150) with try; print with on BalanceError catch (e); print "done" in finally.
Starter code
void main() {
// Define BalanceError class
// Define BankAccount class
// try + on BalanceError + finally
}Sample solution
class BalanceError implements Exception {
final String message;
BalanceError(this.message);
String toString() => message;
}
class BankAccount {
int balance;
BankAccount(this.balance);
void withdraw(int amount) {
if (balance < amount) throw BalanceError("insufficient balance");
}
}
void main() {
final a = BankAccount(100);
try {
a.withdraw(150);
} on BalanceError catch (e) {
print(e);
} finally {
print("done");
}
}Expected output
insufficient balance done
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does BankAccount.withdraw throw?
void withdraw(int amount) {
if (balance < amount) throw Exception("insufficient");
}- when balance is less than amount
- when balance equals amount Correct answer
- when balance is a class field
- always
Explanation: It throws on insufficient balance.
2 Match the exception tools
| Term | Meaning |
|---|---|
try |
holds risky code |
throw |
raises the error |
catch |
catches the error |
finally |
does cleanup |