-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBankExample.java
More file actions
51 lines (43 loc) · 1.46 KB
/
BankExample.java
File metadata and controls
51 lines (43 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class BankAccount {
private String owner;
private double balance;
public BankAccount(String owner, double startingBalance) {
this.owner = owner;
this.balance = startingBalance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount + ", New balance: " + balance);
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(
"Withdrawal of " + amount + " denied for " + owner +
". Current balance is only " + balance + "."
);
}
balance -= amount;
System.out.println("Withdrew: " + amount + ", New balance: " + balance);
}
public double getBalance() {
return balance;
}
}
public class BankExample {
public static void main(String[] args) {
BankAccount account = new BankAccount("Harmeet", 1000.0);
try {
account.deposit(500.0);
account.withdraw(200.0);
account.withdraw(2000.0);
} catch (InsufficientFundsException e) {
System.out.println("Custom Exception Caught: " + e.getMessage());
}
System.out.println("Final balance: " + account.getBalance());
}
}