Custom Exceptions

In this exercise, you will learn how to create and handle **Custom Exceptions** in Java. You will define your own exception classes to represent specific errors within a program and use the throw and throws keywords to efficiently generate and handle these errors. This approach will allow you to improve the **robustness** and **maintainability** of your applications by properly handling exceptional situations in your code.

Topic

File Handling and Advanced Exceptions

Java Exercise

In this exercise, you will create a Java program that implements **Custom Exceptions**. To do this, you will define an **exception class** called InsufficientBalanceException, which will be triggered when a user attempts to withdraw more money than they have available in their bank account. Next, you'll implement a BankAccount class with a withdraw() method that will throw this exception when necessary.

Instructions:

  1. Create a **custom exception class** called InsufficientBalanceException that extends Exception and has a constructor that receives an error message.
  2. Create a **class** called BankAccount with balance and holder attributes, and implement a withdraw(double amount) method that checks for a sufficient balance. If there isn't one, throw an instance of InsufficientBalanceException.
  3. In the main() method, create an instance of BankAccount and test the withdrawal functionality, handling the exception with a try-catch block.

This exercise will help you understand how to create and use **Custom Exceptions** in Java to improve error handling and application security.


// Definition of a custom exception
class InsufficientBalanceException extends Exception {
    public InsufficientBalanceException(String message) {
        super(message);
    }
}

// BankAccount class
class BankAccount {
    private String accountHolder;
    private double balance;

    public BankAccount(String accountHolder, double balance) {
        this.accountHolder = accountHolder;
        this.balance = balance;
    }

    public void withdraw(double amount) throws InsufficientBalanceException {
        if (amount > balance) {
            throw new InsufficientBalanceException("Insufficient balance to withdraw " + amount + "€");
        }
        balance -= amount;
        System.out.println("Successful withdrawal of " + amount + "€. Remaining balance: " + balance + "€");
    }

    public void showBalance() {
        System.out.println("Current balance of " + accountHolder + ": " + balance + "€");
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a bank account with an initial balance
        BankAccount account = new BankAccount("John Doe", 500);

        // Show initial balance
        account.showBalance();

        // Try to perform withdrawal operations
        try {
            account.withdraw(200);
            account.withdraw(400); // This withdrawal will generate an exception
        } catch (InsufficientBalanceException e) {
            System.out.println("Error: " + e.getMessage());
        }

        // Show final balance
        account.showBalance();
    }
}

 Output:

John Doe's current balance: €500
Successful withdrawal of €200. Remaining balance: €300
Error: Insufficient balance to withdraw €400
John Doe's current balance: €300

This program demonstrates how to use **Custom Exceptions** in Java to improve error handling. The InsufficientBalanceException class allows you to catch and handle unauthorized withdrawal attempts in the BankAccount class. When you run the program, you can see that a valid withdrawal operation completes successfully, while an excessive withdrawal attempt generates a handled exception.


 Share this JAVA exercise