Question:
Consider the following BankAccount
class:
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}
public void deposit(double amount) {
if (amount <= 0) {
// throw exception here
} else {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount <= 0) {
// throw exception here
} else if (amount > balance) {
// throw exception here
} else {
balance -= amount;
}
}
public double getBalance() {
return balance;
}
}
You need to modify the deposit
and withdraw
methods in the BankAccount
class to throw appropriate exceptions in case of invalid inputs.
Which type of exception should you throw in each case, and how would you modify the methods to throw those exceptions? Provide the modified code for both methods.
Answer:
To throw appropriate exceptions in the deposit
and withdraw
methods, we should use the IllegalArgumentException
and InsufficientFundsException
respectively.
Here's the modified code for the BankAccount
class:
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Deposit amount must be greater than 0");
} else {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal amount must be greater than 0");
} else if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds to withdraw");
} else {
balance -= amount;
}
}
public double getBalance() {
return balance;
}
}
Explanation:
In the deposit
method, we throw an IllegalArgumentException
when the amount
argument is less than or equal to 0. The exception message provides a clear explanation of the issue.
In the withdraw
method, we first check if the amount
argument is less than or equal to 0. If it is, we throw an IllegalArgumentException
with an appropriate message. If the amount
is greater than the balance, we throw a custom InsufficientFundsException
. Otherwise, we deduct the amount
from the balance.
This approach ensures that any invalid deposits or withdrawals will be caught and appropriate exceptions will be thrown, providing useful information about the nature of the error.