easy
Exception Handling
Custom InsufficientBalanceException
Create a checked exception InsufficientBalanceException and a BankAccount whose withdraw(amount) throws it when amount > balance. On success, subtract and return the new balance.
Interview angle
Interviewers want to see when you choose checked vs unchecked, and that the exception carries a useful message (requested amount + current balance).
Starter code
class InsufficientBalanceException extends Exception {
// TODO
}
class BankAccount {
private double balance;
BankAccount(double balance) { this.balance = balance; }
public double withdraw(double amount) throws InsufficientBalanceException {
// TODO
return 0;
}
}
public class BankDemo {
public static void main(String[] args) {
BankAccount a = new BankAccount(1000);
try {
System.out.println(a.withdraw(1500));
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
}
}
}Solution
class InsufficientBalanceException extends Exception {
InsufficientBalanceException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
BankAccount(double balance) { this.balance = balance; }
public double withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException(
"Need " + amount + " but balance is " + balance
);
}
balance -= amount;
return balance;
}
}
public class BankDemo {
public static void main(String[] args) {
BankAccount a = new BankAccount(1000);
try {
System.out.println(a.withdraw(1500));
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
}
}
}