Summary - Exception basics
- Java course
- Beginner
- Lesson 111/116
- 5 min
Combine try/catch/finally and throw to write a bank account class.
Summary - Exception basics
In this group you learned try/catch, finally, throw, the exception hierarchy and multiple catch. You can now write an Account class, use throw for a balance check in withdraw, and handle it with try/catch/finally at the call site.
This summary lesson has 5 steps and includes one code task. The bank account example brings everything you learned together.
Practice Bank account
Write an Account class: a double balance field, an Account(double b) constructor and a void withdraw(double amount) method. withdraw should throw new IllegalStateException("Yetersiz bakiye") if amount > balance. In main create Account acc = new Account(100); and call acc.withdraw(150); catch IllegalStateException with try/catch and print Hata: with getMessage(); print İşlem tamam in finally.
Starter code
public class Main {
public static void main(String[] args) {
Account acc = new Account(100);
// call withdraw, handle with try/catch/finally
}
}
class Account {
double balance;
Account(double b) { this.balance = b; }
// write the withdraw method: throw if amount > balance
}Sample solution
// inside Account:
void withdraw(double amount) {
if (amount > balance) {
throw new IllegalStateException("Yetersiz bakiye");
}
balance -= amount;
}
// inside main:
try {
acc.withdraw(150);
} catch (IllegalStateException e) {
System.out.println("Hata: " + e.getMessage());
} finally {
System.out.println("İşlem tamam");
}Expected output
Hata: Yetersiz bakiye İşlem tamam
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does the finally block run?
- Only when there is an exception
- Only on return
- Always Correct answer
- Only when there is no exception
Explanation: finally runs in every case, whether or not an exception occurs.
2 Throw for insufficient balance
if (amount > balance) {
throw new IllegalStateException("____");
}
if (amount > balance) {
throw new IllegalStateException("Yetersiz bakiye");
}
Explanation: the IllegalStateException message is written with Turkish characters.
3 Match each keyword to its purpose
| Term | Meaning |
|---|---|
try |
Risky code |
catch |
Catch error |
finally |
Cleanup |
throw |
Throw exception |