Stop 07 · Exception Handling & File I/OTopics · 5/8

Custom Exceptions

Part of the Java Roadmap

In short

"Something went wrong" helps nobody. A custom exception like OrderNotFoundException tells the reader exactly what failed, and lets callers catch just that case.

You can create your own exception classes by extending Exception (checked) or RuntimeException (unchecked) to describe errors specific to your application.

The jaadu sorts coloured complaint forms into a row of labelled trays on a busy railway office counter.

Think of it like this

Labelled complaint forms

A railway office in Chennai has one generic complaint box, and every letter must be read to know what it is about. Then they print special forms: Lost Luggage, Refund Delay, Seat Problem. Each lands on the right desk straight away. Custom exceptions are those labelled forms.

Watch it happen

Two ways to build your own exception

extends Exception (checked)

  • Caller must catch or declare it
  • For problems a careful caller can still hit
  • Example: OrderNotFoundException

extends RuntimeException (unchecked)

  • No forced handling
  • For invalid input or broken rules from the caller
  • Example: InvalidPincodeException

Pick the parent based on who is at fault. Most modern frameworks lean on unchecked exceptions, but checked ones are still useful for recoverable situations.

The big ideas

What you need to know

Name ends with Exception

Use clear names like PaymentDeclinedException. The name alone should explain the problem.

Pass a message up

Call super(message) in the constructor so getMessage() shows a helpful description.

Keep the cause

Add a constructor that takes Throwable cause and call super(message, cause). The original stack trace is kept for debugging.

Carry extra data

A custom exception is a normal class. Add fields like orderId so the catch block can use them.

See it in code

Walk through the code

java
1// Checked: callers must plan for a missing order2public class OrderNotFoundException extends Exception {3    private final String orderId;4 5    public OrderNotFoundException(String orderId) {6        super("No order found with id " + orderId);7        this.orderId = orderId;8    }9 10    public OrderNotFoundException(String orderId, Throwable cause) {11        super("No order found with id " + orderId, cause);12        this.orderId = orderId;13    }14 15    public String getOrderId() {16        return orderId;17    }18}19 20// Unchecked: a bad pincode is the caller's mistake, so fail fast21class InvalidPincodeException extends RuntimeException {22    public InvalidPincodeException(String pincode) {23        super("Pincode must be 6 digits, got: " + pincode);24    }25}26 27class DeliveryCheck {28    static void checkPincode(String pin) {29        if (pin == null || !pin.matches("[0-9]{6}")) {30            throw new InvalidPincodeException(pin);31        }32    }33}

1/4Extending Exception makes it checked. The orderId field travels with the error.

Two custom exceptions for a food delivery app. OrderNotFoundException carries the order id; InvalidPincodeException fails fast on bad input.

Save yourself the pain

Common mistakes

Oops

Catching a low-level exception and throwing a new custom one without the cause.

Do this instead

throw new OrderNotFoundException(id, e); Passing e keeps the original stack trace, which you will need when debugging.

Oops

Creating a custom exception for every tiny case: NameTooShortException, NameTooLongException ...

Do this instead

Use built-ins like IllegalArgumentException when they fit. Create custom types when callers need to handle the case differently.

Oops

Extending Throwable or Error directly.

Do this instead

Extend Exception or RuntimeException. Error is reserved for serious JVM problems.

Your mission

Exceptions for a cinema app

~25 min

Quick check

You want callers to be forced by the compiler to handle your new exception. What should it extend?

Go deeper

  1. 1Create InsufficientFundsException for your bank project.
  2. 2Pass a clear message and the original cause to the super constructor.
  3. 3Decide whether your exception should be checked or unchecked, and why.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge