Dart
Summary - Exceptions
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.
Exercise 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).
Show example 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);
}
}
Exercise 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.
Show example 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");
}
}
Test yourself
-
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
- when balance is a class field
- always
Show answer
when balance equals amount — It throws on insufficient balance.
-
Match the exception tools
- try
- holds risky code
- throw
- raises the error
- catch
- catches the error
- finally
- does cleanup
Next lesson: Future