Java Custom Exceptions

Summary: In this tutorial, you will learn how to learn about Java custom exceptions and how to use them effectively.

Introduction to Java custom exceptions

In Java, exceptions are classes, which means you can define your own exception that extends a built-in exception class. These custom exceptions are often referred to as user-defined exceptions.

Custom exceptions are useful when you want to handle specific error conditions in your code, which are not covered by the standard Java exception classes.

When defining an exception, you typically extend the built-in exception class like this:

class MyCustomException extends Exception {
    // ...
}Code language: Java (java)

In this example, the MyCustomException inherits from the built-in Exception class. By convention, the name of an exception class ends with the word “Exception“.

The MyCustomException class may have a constructor that accepts a string. If so, you need to call the constructor of the Exception class in the constructor of the user-defined exception using super() as follows:

class MyCustomException extends Exception {
    public MyCustomException(String message) {
            super(message);
            // ... 
    }
}Code language: Java (java)

Java custom exception example

Let’s take an example to understand custom exceptions.

First, define a class BankAccount that represents bank accounts:

public class Account {
    private String accountNo;
    private double balance;

    public Account(String accountNo, double initialBalance) {
        this.accountNo = accountNo;
        this.balance = initialBalance;
    }

    public void withdraw(double amount) {
        if (amount > balance) {
            var message = String.format("The withdrawal amount (%.2f) is more than balance (%.2f)",
                    amount,
                    balance);
            throw new IllegalArgumentException(message);
        }

        this.balance -= amount;
    }

    @Override
    public String toString() {
        return String.format("%s: $%.2f", accountNo, balance);
    }
}Code language: Java (java)

Please note that for brevity, we have included only the necessary fields and methods in the BankAccount class.

The withdraw() method checks the withdrawal amount against the current balance and throws an IllegalArgumentException if it is more than the balance. Otherwise, it deducts the withdrawal amount from the balance.

The built-in IllegalArgumentException works fine except that it doesn’t reflect the banking business.

To make it more obvious, you can create a custom exception like InsufficientFundException.

Second, define the InsufficientFundException class that extends the Exception class:

public class InsufficientFundException extends Exception {
    public InsufficientFundException(String message) {
        super(message);
    }
}Code language: Java (java)

The InsufficientFundException class extends the Exception class and has a constructor that accepts a string which is the error message.

Third, throw the InsufficientFundException exception in the withdraw() method of the BankAccount class instead of using the IllegalArgumentException class:

public class BankAccount {
    private String accountNo;
    private double balance;

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

    public void withdraw(double amount) throws InsufficientFundException {
        if (amount > balance) {
            var message = String.format("The withdrawal amount (%.2f) is more than balance (%.2f)",
                    amount,
                    balance);
            throw new InsufficientFundException(message);
        }

        this.balance -= amount;
    }

    @Override
    public String toString() {
        return String.format("%s: $%.2f", accountNo, balance);
    }
}Code language: Java (java)

Finally, use the BankAccount class and handle the custom exception InsufficientFundException in the main() method of the program:

public class App {
    public static void main(String[] args) {
        var account = new BankAccount("CJ101A", 100);

        try {
            account.withdraw(120);
        } catch (InsufficientFundException ex) {
            System.out.println(ex.getMessage());
        }

        System.out.println(account);
    }
}Code language: Java (java)

Output:

The withdrawal amount (120.00) is more than balance (100.00)
CJ101A: $100.00Code language: Java (java)

In this example, we create a new BankAccount object with an initial balance of 100 and attempt to withdraw 120 from the account. As a result, it throws the InsufficientFundException exception, which is caught by the catch block.

Summary

  • Extend the built-in exception class to define custom exceptions in Java.