← Back to Home

Custom Exceptions

Custom exceptions are user-defined exception classes created to represent application-specific error conditions. They make error handling clearer, more meaningful, and domain-focused instead of relying on generic Java exceptions.

This is a high-frequency interview topic, especially in real-world and enterprise Java.

What Is a Custom Exception?

  • A class created by the programmer
  • Extends Exception (checked) or RuntimeException (unchecked)
  • Represents business-rule violations
  • Improves readability and maintainability
class InvalidAgeException extends Exception {
}
          

Why Custom Exceptions Are Needed

  • Generic exceptions lack business meaning
  • Improves error clarity
  • Enables domain-specific handling
  • Cleaner APIs and logs
  • Better debugging and maintenance

❌ Bad practice:

throw new Exception("Error");
          

✔ Good practice:

throw new InvalidAgeException("Age must be >= 18");
          

Types of Custom Exceptions

1️⃣ Checked Custom Exception

Extends Exception. Must be handled or declared.

class InvalidAgeException extends Exception {

    InvalidAgeException(String message) {
        super(message);
    }
}
          

Usage

void validateAge(int age) throws InvalidAgeException {
    if (age < 18) {
        throw new InvalidAgeException("Not eligible to vote");
    }
}
          

2️⃣ Unchecked Custom Exception

Extends RuntimeException. Not forced to be handled.

class InvalidAgeException extends RuntimeException {

    InvalidAgeException(String message) {
        super(message);
    }
}
          

Usage

void validateAge(int age) {
    if (age < 18) {
        throw new InvalidAgeException("Age below 18");
    }
}
          

Checked vs Unchecked Custom Exceptions

Aspect Checked Unchecked
Parent class Exception RuntimeException
Compiler check ✅ Yes ❌ No
Must handle ✅ Yes ❌ No
Use case Recoverable Programming / rule violation

Best Practice: Add Constructors

class BusinessException extends Exception {

    BusinessException() {
        super();
    }

    BusinessException(String message) {
        super(message);
    }

    BusinessException(String message, Throwable cause) {
        super(message, cause);
    }
}
          
  • ✔ Supports exception chaining
  • ✔ Production-ready design

Exception Chaining (Important)

try {
    int x = 10 / 0;
} catch (ArithmeticException e) {
    throw new BusinessException("Calculation failed", e);
}
          
  • ✔ Preserves original cause
  • ✔ Helps debugging

Naming Conventions

  • Must end with Exception
  • Should describe error condition clearly

Examples:

  • InvalidAgeException
  • InsufficientBalanceException
  • UserNotFoundException

Real-World Example (Interview-Friendly)

class InsufficientBalanceException extends Exception {

    InsufficientBalanceException(String msg) {
        super(msg);
    }
}

class BankAccount {
    private double balance = 5000;

    void withdraw(double amount) throws InsufficientBalanceException {
        if (amount > balance) {
            throw new InsufficientBalanceException("Insufficient funds");
        }
        balance -= amount;
    }
}
          

When to Use Custom Exceptions

  • Business rule violations
  • Validation failures
  • Domain-specific errors
  • Service and API layers

When NOT to Use Custom Exceptions

  • For normal control flow
  • When standard exceptions already fit
  • For trivial or generic failures

Common Beginner Mistakes

  • Extending Throwable or Error
  • Creating too many custom exceptions
  • Using checked exceptions everywhere
  • Not passing meaningful messages
  • Ignoring exception chaining

Interview-Ready Answers

Short Answer

A custom exception is a user-defined exception used to represent application-specific error conditions.

Detailed Answer

In Java, custom exceptions are created by extending Exception or RuntimeException. They allow developers to represent business-specific errors clearly and handle them meaningfully. Checked custom exceptions must be handled or declared, while unchecked ones are optional.

Key Takeaway

Custom exceptions express business intent. They turn error handling from a technical necessity into a clear, readable, and maintainable design feature.