The following code example demonstrates how to Create a Custom Exception in Java for a bank Class.
Write a program that throws exceptions if the bank balance drops below 1000 due to any transaction.
Solution
// Custom exception class for insufficient balance
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// BankAccount class representing a bank account
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Method to deposit money into the account
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}
// Method to withdraw money from the account
public void withdraw(double amount) throws InsufficientBalanceException {
if (balance - amount < 1000) {
throw new InsufficientBalanceException("Insufficient balance. Minimum balance of 1000 required.");
}
balance -= amount;
System.out.println("Withdrawn: " + amount);
}
// Method to check the account balance
public double getBalance() {
return balance;
}
}
// Main class to demonstrate the program
public class BankAccountExceptionDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount(2000);
try {
account.withdraw(1500); // Withdraw an amount that doesn't drop the balance below 1000
account.deposit(500); // Deposit an amount
account.withdraw(1000); // Withdraw an amount that drops the balance below 1000 (should throw an exception)
} catch (InsufficientBalanceException e) {
System.out.println("Exception caught: " + e.getMessage());
}
System.out.println("Current Balance: " + account.getBalance());
}
}
In this program:
- We create a custom exception class
InsufficientBalanceException
to represent the scenario of insufficient balance. - The
BankAccount
class represents a bank account with methods for depositing (deposit
) and withdrawing (withdraw
) money. Thewithdraw
method checks if the balance would drop below 1000 after the withdrawal and throws the custom exception if necessary. - In the
main
method, we create an instance of theBankAccount
class with an initial balance of 2000. We perform a series of transactions, including a withdrawal that would drop the balance below 1000. When the custom exception is thrown, we catch it and print the exception message.
This program demonstrates how to throw and catch a custom exception when the bank balance drops below 1000 due to a transaction.
Further Reading
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go