Write a program to withraw money from a bank account, if the withdrawn money is greater than the balance, then it throws NoMoneyException
.
$ javac Program.java
$ java Program
import java.lang.System;
// Entry point of the program.
public class Program {
public static void main(String[] args) {
BankAccount account = new BankAccount("Steve Jobs", 5000.0);
try {
// Attempt to withdraw `100000.0`, which is more than the balance.
account.withdraw(100000.0);
} catch (NoMoneyException e) {
System.out.println("Exception Message: " + e.getMessage());
} finally {
// Will stay unchanged i.e. `5000.0`.
System.out.println("Balance After Transaction: " + account.getBalance());
}
}
}
// This `Exception` is thrown by the `BankAccount.withdraw` if entered amount is
// more than the available balance.
class NoMoneyException extends Exception {
public NoMoneyException(String message) {
super(message);
}
}
// Minimal `BankAccount` with customer's `name` and `balance`.
// `withdraw` method throws `NoMoneyException` if entered amount is more than
// the available balance.
class BankAccount {
private String name;
private double balance;
public BankAccount(String name, double balance) {
this.name = name;
this.balance = balance;
}
public void withdraw(double amount) throws NoMoneyException {
if (balance < amount) {
throw new NoMoneyException(amount + " is more than the balance of " + balance);
}
balance -= amount;
}
// Public getters.
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
}
right-click & select “Open image in new tab” for larger image.