100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Java

Custom Exceptions in Java

Learn how to define and throw your own checked or unchecked exception classes in Java for clearer, domain-specific error handling.

Exception HandlingIntermediate8 min readJul 7, 2026
Analogies

1. Introduction

While Java's built-in exceptions (like IllegalArgumentException or IOException) cover many common cases, real applications often have domain-specific error conditions — such as InsufficientFundsException in a banking app — that are better represented by custom exception classes.

🏏

Cricket analogy: Standard umpiring signals like 'wide' or 'no-ball' cover common infractions, but a domain-specific rule violation like a bowler's suspicious action needs a specialized report to the match referee, just as InsufficientFundsException handles a domain-specific banking error.

A custom exception is simply a class that extends Exception (making it checked) or RuntimeException (making it unchecked), giving it a clear, self-documenting name and the ability to carry extra context about the failure.

🏏

Cricket analogy: A specialized 'BallTamperingViolation' report, filed by extending the standard misconduct report format, gives officials a clearly named, context-rich record rather than a vague foul, just as a custom exception extends Exception or RuntimeException to add clarity.

2. Syntax

java
// Checked custom exception
public class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

// Unchecked custom exception
public class InvalidAgeException extends RuntimeException {
    public InvalidAgeException(String message) {
        super(message);
    }
}

// Throwing a custom exception
throw new InsufficientFundsException("Balance too low for withdrawal");

3. Explanation

To create a custom exception, extend either Exception or RuntimeException depending on whether you want callers to be forced to handle it (checked) or not (unchecked). By convention, custom exception classes provide constructors mirroring their parent — typically a no-arg constructor, a String message constructor, and a String message plus Throwable cause constructor — so the exception integrates well with existing exception-handling code and preserves the original cause chain.

🏏

Cricket analogy: Choosing to file a mandatory disciplinary report that every match referee must formally address, versus an optional advisory note officials can ignore, mirrors choosing checked Exception versus unchecked RuntimeException; and providing three report formats—blank, with-a-reason, and with-a-reason-plus-video-evidence—mirrors the standard constructor set.

The throw keyword is used to actually raise an instance of the exception (throw new MyException(...)), while the throws keyword appears in a method's signature to declare that the method may propagate a checked exception to its caller, without handling it itself.

🏏

Cricket analogy: An umpire actively raising his finger to give a batsman out is like the throw keyword actually triggering the dismissal, while the match rulebook's clause stating 'a bowler's action may be reported for review' without resolving it itself is like throws, declaring the possibility without handling it.

Exam trap: throw (no 's') is a statement used inside a method body to raise an exception instance. throws (with 's') is a clause in the method signature declaring which checked exceptions the method might propagate. Mixing these up is a very common exam question.

4. Example

java
class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

public class CustomExceptionDemo {
    static void withdraw(double balance, double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException("Cannot withdraw " + amount + ", balance is " + balance);
        }
        System.out.println("Withdrawal of " + amount + " successful.");
    }

    public static void main(String[] args) {
        try {
            withdraw(100.0, 150.0);
        } catch (InsufficientFundsException e) {
            System.out.println("Transaction failed: " + e.getMessage());
        }
    }
}

5. Output

text
Transaction failed: Cannot withdraw 150.0, balance is 100.0

6. Key Takeaways

  • A custom exception is a class extending Exception (checked) or RuntimeException (unchecked).
  • Custom exception classes typically provide constructors matching the parent, especially the String message constructor.
  • throw raises an exception instance; throws declares in a method signature that a checked exception may propagate.
  • Custom exceptions give clearer, more domain-specific error names than generic built-in exceptions.
  • Methods declaring a checked custom exception with throws force callers to catch or re-declare it.

Practice what you learned

Was this page helpful?

Topics covered

#Java#JavaProgrammingStudyNotes#Programming#CustomExceptionsInJava#Custom#Exceptions#Syntax#Explanation#ErrorHandling#StudyNotes#SkillVeris