This example simulates a banking system where you need to withdraw money from an account. The method checks if the account balance is sufficient for the withdrawal, and if not, it throws a custom exception.
// Step 1: Define a custom exception for insufficient funds
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message); // Pass the message to the superclass constructor
}
}
class BankAccount {
private double balance;
// Constructor to initialize the balance
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Step 2: Method that throws the custom exception if funds are insufficient
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
// Step 3: Throw the custom exception
throw new InsufficientFundsException("Insufficient funds. Your balance is " + balance + ", but you tried to withdraw " + amount);
}
balance -= amount;
System.out.println("Withdrawal successful! New balance: " + balance);
}
// Method to get the current balance
public double getBalance() {
return balance;
}
}
public class ThrowsExample {
public static void main(String[] args) {
// Step 4: Create a BankAccount object with an initial balance
BankAccount account = new BankAccount(100.00);
try {
// Attempt to withdraw more money than is available in the account
account.withdraw(90.00);
} catch (InsufficientFundsException e) {
// Handle the exception if it occurs
System.out.println("Exception caught: " + e.getMessage());
}
// Check the balance after the withdrawal attempt
System.out.println("Final balance: " + account.getBalance());
}
}
Comments
Post a Comment