Java Custom Exception

Introduction

Java provides many built-in exception classes such as ArithmeticException, NullPointerException, IOException, and ArrayIndexOutOfBoundsException to handle common runtime and compile-time errors. However, in real-world applications, developers often need to handle business-specific situations that are not adequately represented by Java’s built-in exceptions.

For example, a banking application may need to report Insufficient Balance, an online shopping system may need to indicate Out of Stock.

To handle such scenarios, Java allows developers to create their own exception classes, known as Custom Exceptions or User-Defined Exceptions.

A custom exception is created by extending either the Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions).

What is a Java Custom Exception?

A Custom Exception is a user-defined exception class created by extending one of Java’s exception classes.

It allows developers to represent application-specific error conditions with meaningful names and messages.

For example:

  • InvalidAgeException
  • InsufficientBalanceException
  • InvalidProductException
  • OrderNotFoundException
  • EmployeeNotFoundException

Using descriptive exception names makes the code easier to understand and maintain.

Why Use Custom Exceptions?

Custom exceptions offer several benefits:

  • Represent business-specific errors
  • Improve code readability
  • Provide meaningful error messages
  • Separate business logic from error handling
  • Make debugging easier
  • Improve API design
  • Encourage reusable and maintainable code

Instead of throwing generic exceptions, developers can throw exceptions that clearly describe the actual problem.

Types of Custom Exceptions

Java supports two types of custom exceptions.

1. Checked Custom Exception

A checked custom exception extends the Exception class.

The compiler requires it to be handled using try-catch or declared with the throws keyword.

Example:


class InvalidAgeException
        extends Exception {
}

2. Unchecked Custom Exception

An unchecked custom exception extends the RuntimeException class.

Handling it is optional because it is checked at runtime.

Example:


class InvalidAgeException
        extends RuntimeException {
}

Creating a Checked Custom Exception

The following example creates a checked custom exception.


class InvalidAgeException
        extends Exception {
    InvalidAgeException(String message) {
        super(message);
    }
}

The constructor passes the error message to the parent Exception class.

Throwing a Custom Exception

Once the custom exception class is created, it can be thrown using the throw keyword.


public class Main {
    static void validateAge(int age)
            throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException(
                "Age must be at least 18."
            );
        }
        System.out.println(
            "Eligible to vote."
        );
    }
}

The method declares the exception using the throws keyword.

Handling a Custom Exception

A custom exception can be handled using a try-catch block.


public class Main {
    public static void main(String[] args) {
        try {
            validateAge(15);
        } catch (InvalidAgeException e) {
            System.out.println(
                e.getMessage()
            );
        }
    }
    static void validateAge(int age)
            throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException(
                "Age must be at least 18."
            );
        }
    }
}

Output


Age must be at least 18.

The application handles the custom exception gracefully.

Creating an Unchecked Custom Exception

An unchecked custom exception extends RuntimeException.


class InvalidSalaryException
        extends RuntimeException {
    InvalidSalaryException(String message) {
        super(message);
    }
}
Using it:
if (salary < 0) {
    throw new InvalidSalaryException(
        "Salary cannot be negative."
    );
}

Unlike checked exceptions, the compiler does not require this exception to be handled.

Custom Exception with Additional Information

Custom exceptions can store additional details.


class ProductNotFoundException
        extends Exception {
    private int productId;
    ProductNotFoundException(
            int productId,
            String message) {
        super(message);
        this.productId = productId;
    }
    public int getProductId() {
        return productId;
    }
}

This allows developers to retrieve more information about the error.

Real-Life Example

Suppose an online banking system allows users to withdraw money.


class InsufficientBalanceException
        extends Exception {
    InsufficientBalanceException(
            String message) {
        super(message);
    }
}
public class Bank {
    static void withdraw(
            double balance,
            double amount)
            throws InsufficientBalanceException {
        if (amount > balance) {
            throw new InsufficientBalanceException(
                "Insufficient account balance."
            );
        }
        System.out.println(
            "Withdrawal successful."
        );
    }
    public static void main(String[] args) {
        try {
            withdraw(5000, 7000);
        } catch (
            InsufficientBalanceException e) {
            System.out.println(
                e.getMessage()
            );
        }
    }
}

Output

Insufficient account balance.

This custom exception clearly communicates the business rule that was violated.

Checked vs Unchecked Custom Exceptions

Checked Custom Exception Unchecked Custom Exception
Extends Exception Extends RuntimeException
Checked at compile time Checked at runtime
Must be handled or declared Handling is optional
Suitable for recoverable conditions Suitable for programming errors or validation failures
Uses throws or try-catch May be left unhandled

Custom Exception vs Built-in Exception

Built-in Exception Custom Exception
Provided by Java Created by developers
Represents common programming errors Represents application-specific errors
Generic names Meaningful business-specific names
Limited to predefined scenarios Fully customizable

Advantages of Custom Exceptions

  • Improve code readability
  • Represent business logic clearly
  • Provide meaningful error messages
  • Simplify debugging
  • Support reusable APIs
  • Make applications easier to maintain
  • Improve overall code organization

Common Mistakes

1. Extending the Wrong Class

Choose the correct base class:

  • Extend Exception for checked exceptions.
  • Extend RuntimeException for unchecked exceptions.

2. Using Generic Exception Names

Avoid names like:


class MyException
        extends Exception {
}

Prefer descriptive names:


class InvalidEmployeeIdException
        extends Exception {
}

Meaningful names make the purpose of the exception immediately clear.

3. Throwing Generic Exception

Instead of:


throw new Exception("Error");

Use:


throw new InvalidAgeException(
    "Age must be at least 18."
);

4. Ignoring Exception Messages

Always provide meaningful messages that help identify the problem.

5. Creating Too Many Custom Exceptions

Only create custom exceptions when they add clarity and represent distinct business conditions. Avoid unnecessary duplication.

Best Practices

📖
Best Practices:
  • Use meaningful exception class names.
  • Extend the appropriate superclass (Exception or RuntimeException).
  • Include descriptive error messages.
  • Add constructors that accept messages and causes when appropriate.
  • Keep exception classes focused and lightweight.
  • Document custom exceptions using Javadoc.
  • Catch exceptions only where recovery is possible.
  • Use custom exceptions for business rules rather than programming errors.

Conclusion

Java Custom Exceptions enable developers to create meaningful, application-specific error types that go beyond Java's built-in exceptions. By extending Exception or RuntimeException, developers can model business rules more accurately, improve code readability, and provide informative error messages that make applications easier to debug and maintain.

Related Java Tutorials