Interview Q&A / Java

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you create a custom exception in Java?

SHORT ANSWER

Extend Exception for a checked custom exception or RuntimeException for an unchecked one, and add constructors that pass the message and optionally a cause to the parent. Use it to express a business rule clearly.

Explain it simply

A built-in exception like IllegalArgumentException is a generic "something is wrong" letter. A custom exception such as InsufficientBalanceException is a letter with a clear heading, so whoever receives it knows exactly which rule was broken.

Example

java
class InsufficientBalanceException extends Exception {          // checked
    private final double shortBy;
    InsufficientBalanceException(String msg, double shortBy) {
        super(msg);
        this.shortBy = shortBy;
    }
    double getShortBy() { return shortBy; }
}

static void pay(double balance, double bill) throws InsufficientBalanceException {
    if (bill > balance) throw new InsufficientBalanceException("Low balance", bill - balance);
}

try {
    pay(200, 350);
} catch (InsufficientBalanceException e) {
    System.out.println(e.getMessage() + ", short by " + e.getShortBy());
    // prints: Low balance, short by 150.0
}

What to say in the interview

"I extend Exception if callers should be forced to handle the problem, and RuntimeException if it signals a programming or unrecoverable error. I provide a constructor taking a message and another taking a message and a cause, so the original exception is not lost. I name the class after the problem and end it with Exception."

Common mistakes

  • Extending Throwable directly.
  • Dropping the original cause when wrapping another exception.

#java#exceptions#custom-exception

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.