Custom Exceptions: Your Own Errors

Custom Exceptions: Your Own Errors in Java: When something fails inspection on a factory floor, the quality department does not scrawl "it's broken" on a scrap…

The Analogy: The Non-Conformance Reports In A Quality Department

When something fails inspection on a factory floor, the quality department does not scrawl "it's broken" on a scrap of paper and hope the next person understands. It raises a non-conformance report on a purpose-designed form, and there is a family of forms, not one. A dimensional NCR has boxes for the measured value, the tolerance, and the drawing number. A material NCR has boxes for the batch, the certificate reference, and the supplier. A finish NCR captures the defect area and the coating spec. Each form is a distinct type under the common heading "non-conformance report," and each carries the structured fields that the desk receiving it will actually need to act. A custom exception is one of these forms: a named type, built for a specific domain failure, carrying the exact data a handler needs rather than a free-text sentence.

The structured fields are the whole point. When a dimensional NCR arrives, the responder reads "out by 0.4mm against a 0.1mm tolerance" straight from the boxes and knows immediately whether to scrap or rework. They do not have to read a paragraph and infer the numbers. A custom exception that carries the requested quantity and the available quantity as fields lets the catch block read those numbers directly, instead of parsing them out of a message string that might be worded differently next release.

The family structure matters as much as the individual forms. Because every NCR sits under one common heading, a supervisor can ask for "every non-conformance on this job" and get all of them, or ask specifically for "the dimensional ones" and get just those. An exception hierarchy works the same way: a base domain exception with specific subtypes lets a handler catch the base to deal with any failure uniformly, or catch a subtype to respond to one kind precisely. The type is what the receiving desk routes on.

The failure mode has two opposite shapes. The first is minting a brand-new form for a failure the standard one already covers -- a proliferation of near-identical report types nobody can keep straight, custom exceptions where IllegalArgumentException would have said everything. The second, and the one this lesson is built around, is the reverse: cramming every distinct failure behind one generic form with a single free-text box. The order team defines one OrderException, throws it for out-of-stock and declined-payment and bad-address alike, and distinguishes them only by the wording of the message. Now every caller who needs to react differently -- retry the payment, reorder the stock, correct the address -- has no typed way to tell them apart, and ends up matching substrings of the message. The type system was right there and the design threw it away.


Syntax or Core Structure

public class Warehouse {

    static class InsufficientStockException extends Exception {
        private final int requested;
        private final int available;

        InsufficientStockException(int requested, int available) {
            super("requested " + requested
                + " but only " + available + " available");
            this.requested = requested;
            this.available = available;
        }

        int shortfall() { return requested - available; }
    }

    static int fulfil(int inStock, int requested)
            throws InsufficientStockException {
        if (requested > inStock) {
            throw new InsufficientStockException(requested, inStock);
        }
        return inStock - requested;
    }

    public static void main(String[] args) {
        try {
            System.out.println("left:     " + fulfil(10, 4));
            System.out.println("left:     " + fulfil(10, 25));
        } catch (InsufficientStockException e) {
            System.out.println("message:  " + e.getMessage());
            System.out.println("short by: " + e.shortfall());
        }
    }
}

Output:

left:     6
message:  requested 25 but only 10 available
short by: 15

The exception carries requested and available as fields and exposes shortfall(), so the catch block reads the shortfall as a number rather than parsing it out of the message. The type itself names the failure, and the fields carry the data a handler needs to act.


Technical Depth: Which Base To Extend, The Constructors To Provide, And Designing A Hierarchy

Extending Exception Versus RuntimeException

The single most consequential decision is which base class you extend, because it decides whether your exception is checked or unchecked.

ExtendKindCallers must handle or declare?Use for
ExceptionCheckedYes, compiler-enforcedA recoverable condition the caller should address
RuntimeExceptionUncheckedNoA programming error or an unrecoverable domain fault
ErrorUncheckedNoNever subclass this in application code

Extend Exception when the caller can plausibly recover and you want the compiler to force a conscious decision -- insufficient funds, a permit expired. Extend RuntimeException when the condition signals a bug or when threading a throws clause through every intermediate method would add noise without safety. Modern Java has drifted toward unchecked domain exceptions for exactly that reason, but checked remains right when recovery is genuinely expected. See [[throws-declaration]] for how the checked choice propagates.

The Constructors Every Exception Should Provide

Throwable offers four standard constructors, and a well-behaved exception forwards to them so it composes with the rest of the exception machinery -- especially cause-chaining. The cause is what preserves the original stack trace when you wrap a lower-level failure.

ConstructorForwards toWhen it is used
Name()super()Frameworks and serialization that reconstruct by reflection
Name(String message)super(message)A plain failure with a human-readable description
Name(String message, Throwable cause)super(message, cause)Wrapping a lower-level exception while adding context
Name(Throwable cause)super(cause)Rethrowing where the cause's message is enough
public class Wrapping {

    static class ConfigException extends RuntimeException {
        private final String key;

        ConfigException(String key, Throwable cause) {
            super("failed to load setting: " + key, cause);
            this.key = key;
        }

        String key() { return key; }
    }

    static int load(String key, String raw) {
        try {
            return Integer.parseInt(raw);
        } catch (NumberFormatException e) {
            throw new ConfigException(key, e);
        }
    }

    public static void main(String[] args) {
        try {
            load("timeout", "3O00");
        } catch (ConfigException e) {
            System.out.println("message:  " + e.getMessage());
            System.out.println("key:      " + e.key());
            System.out.println("cause:    "
                + e.getCause().getClass().getSimpleName());
        }
    }
}

Output:

message:  failed to load setting: timeout
key:      timeout
cause:    NumberFormatException

The ConfigException adds a domain field, key, on top of a readable message, and passes the original NumberFormatException as the cause. A handler gets the domain context and the underlying fault both -- getCause still reveals the number-format failure that started it, which a message-only wrapper would have discarded.

A Family Under One Base: Catching Broad Or Narrow

The real power of custom exceptions shows when you build a small hierarchy. Define one base for a domain, then specific subtypes beneath it. A handler that catches the base copes with any failure in that domain; a handler that catches a subtype responds to one kind precisely. The catch order runs most-specific first, exactly as [[try-catch]] requires.

public class Orders {

    static class OrderException extends Exception {
        OrderException(String message) { super(message); }
    }

    static class OutOfStockException extends OrderException {
        private final String sku;
        OutOfStockException(String sku) {
            super("out of stock: " + sku);
            this.sku = sku;
        }
        String sku() { return sku; }
    }

    static class PaymentDeclinedException extends OrderException {
        PaymentDeclinedException(String reason) {
            super("payment declined: " + reason);
        }
    }

    static void place(String kind) throws OrderException {
        if (kind.equals("stock")) throw new OutOfStockException("A-17");
        if (kind.equals("pay"))   throw new PaymentDeclinedException("expired card");
        System.out.println("placed:   " + kind);
    }

    static void attempt(String kind) {
        try {
            place(kind);
        } catch (OutOfStockException e) {
            System.out.println("reorder:  " + e.sku());
        } catch (OrderException e) {
            System.out.println("generic:  " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        attempt("ok");
        attempt("stock");
        attempt("pay");
    }
}

Output:

placed:   ok
reorder:  A-17
generic:  payment declined: expired card

The out-of-stock case is routed by its specific handler, which reads the sku field directly and reorders. The declined payment has no dedicated handler here, so it falls through to the OrderException catch and is dealt with generically. Adding a PaymentDeclinedException catch later is a purely additive change -- no existing caller breaks, because the types already distinguish the cases. That is the whole argument against the single stringly-typed exception the analogy warned about.


Real World Example: A Stringly-Typed Exception Versus A Typed Hierarchy

Here are the two designs side by side. The first collapses every order failure into one OrderException and hides the distinction in the message text; the caller has no honest way to react differently, so it resorts to contains. The second gives each failure a type, and the caller routes on the type.

public class Checkout {

    // Design A: one exception, distinguished only by message text.
    static class OrderException extends Exception {
        OrderException(String message) { super(message); }
    }

    static void stringly(String kind) throws OrderException {
        if (kind.equals("stock")) throw new OrderException("OUT_OF_STOCK: A-17");
        if (kind.equals("pay"))   throw new OrderException("DECLINED: expired");
        throw new OrderException("UNKNOWN");
    }

    static String routeByMessage(String kind) {
        try {
            stringly(kind);
            return "placed";
        } catch (OrderException e) {
            // The caller is forced to parse the message.
            if (e.getMessage().contains("OUT_OF_STOCK")) return "reorder";
            if (e.getMessage().contains("DECLINED"))     return "retry-pay";
            return "escalate";
        }
    }

    // Design B: a typed hierarchy, routed by catch.
    static class Failure extends Exception {
        Failure(String message) { super(message); }
    }
    static class OutOfStock extends Failure {
        final String sku;
        OutOfStock(String sku) { super("out of stock"); this.sku = sku; }
    }
    static class Declined extends Failure {
        Declined() { super("declined"); }
    }

    static void typed(String kind) throws Failure {
        if (kind.equals("stock")) throw new OutOfStock("A-17");
        if (kind.equals("pay"))   throw new Declined();
        throw new Failure("unknown");
    }

    static String routeByType(String kind) {
        try {
            typed(kind);
            return "placed";
        } catch (OutOfStock e) {
            return "reorder " + e.sku;
        } catch (Declined e) {
            return "retry-pay";
        } catch (Failure e) {
            return "escalate";
        }
    }

    public static void main(String[] args) {
        System.out.println("A stock: " + routeByMessage("stock"));
        System.out.println("A pay:   " + routeByMessage("pay"));
        System.out.println("B stock: " + routeByType("stock"));
        System.out.println("B pay:   " + routeByType("pay"));
        System.out.println("B ok:    " + routeByType("ok"));
    }
}

Output:

A stock: reorder
A pay:   retry-pay
B stock: reorder A-17
B pay:   retry-pay
B ok:    escalate

Both designs produce the same routing today, so a demo makes them look equivalent. They are not. In Design A the string "OUT_OF_STOCK" is a contract nobody declared: the day someone rewords the message to "stock unavailable" for a nicer UI, routeByMessage silently starts escalating every stock shortage, and no compiler warns them. The magic substrings are duplicated across every caller, and the exception carries no structured data -- the SKU is buried in prose, not a field. Design B routes on types the compiler knows about, carries the SKU as a field, and rejects a mismatched catch at compile time.

Design B is not free of judgement, though, and it is worth being honest about its limits. A hierarchy that grows a subtype for every conceivable variation becomes its own burden -- dozens of near-identical exception classes are as hard to navigate as one overloaded message. There is a real design flaw lurking in over-eager hierarchies: deep inheritance chains where an intermediate class exists only to group two leaves invite catching too broadly by accident, so a handler meant for one leaf quietly swallows its sibling. The discipline is to keep the tree shallow -- usually one base and a flat set of subtypes -- add a subtype only when a caller genuinely routes on it, and never mint a custom exception where a standard one already says exactly what happened. See [[throw-keyword]] for when a plain built-in throw is the better call.


Common Mistakes

  1. Extending Exception (checked) without deciding it should be checked. Reaching for extends Exception by reflex forces every caller up the stack to handle or declare it. If the condition is really a programming error, extend RuntimeException instead and spare the codebase a forest of throws clauses.
  1. Swallowing the cause when wrapping. Writing throw new ConfigException("bad config") inside a catch and dropping the caught exception discards the original stack trace. Always pass the cause: throw new ConfigException("bad config", e), so [[finally-block]] cleanup and later debugging still see the root fault.
  1. Encoding data in the message instead of fields. Putting "requested 25, available 10" only in the message forces every handler to parse prose. Store requested and available as fields with accessors; the message is for humans, the fields are for code.
  1. Naming the class without an Exception suffix. A type called BadOrder reads like a domain model, not a failure. The convention is a trailing Exception (or Error for the unchecked-fatal case) so readers know at the throw site what kind of thing it is.
  1. Catching the base when you meant a subtype. Ordering catch (OrderException e) before catch (OutOfStockException e) makes the specific handler unreachable -- and in Java it will not compile. Even when it does compile, catching too broadly swallows siblings you did not mean to handle.
  1. Making domain fields mutable. Leaving requested non-final lets a handler mutate the exception after it is thrown, so two catch blocks up the stack disagree about what happened. Mark carried fields final; an exception is a record of a moment, not a workspace.
  1. Building a deep inheritance tree. Four levels of exception classes where each adds nothing but a name is harder to reason about than a flat base-plus-subtypes. Keep it shallow and add a level only when a real caller routes on it.
  1. Creating a custom exception where a standard one fits. A null argument is NullPointerException, a bad argument is IllegalArgumentException, a bad state is IllegalStateException. Minting MyNullException for these adds a type nobody recognises and buys nothing.
  1. Forgetting the no-arg and message-only constructors. Providing only (int, int) means frameworks and serialization paths that expect a (String) or no-arg constructor cannot reconstruct your exception. Forward to super from the standard set so the type composes with the ecosystem.

Best Practices

  • Choose checked versus unchecked deliberately. Extend Exception when the caller can and should recover; extend RuntimeException for programming errors and faults no caller can sensibly handle. Make the choice a decision, not a default.
  • Carry structured data as final fields. Give the exception the values a handler needs -- the SKU, the requested amount, the offending key -- as final fields with accessors, so callers read data instead of parsing a message.
  • Always chain the cause. When wrapping a lower-level exception, pass it through the (message, cause) constructor so getCause preserves the original stack trace and the root fault is never lost.
  • Keep the hierarchy shallow. Prefer one base exception per domain with a flat set of subtypes. Add a subtype only when a caller genuinely routes on it, and resist grouping levels that carry no behaviour.
  • Name for the failure and suffix with Exception. InsufficientStockException says what went wrong at a glance; the suffix marks it as a throwable at every throw and catch site.
  • Reuse standard exceptions when they fit. Before writing a class, ask whether IllegalArgumentException, IllegalStateException, or NullPointerException already says it. Custom types are for domain failures the standard set cannot express.
  • Provide the standard constructors. Forward to super for the no-arg, message, and message-plus-cause forms so your exception composes with frameworks, logging, and serialization.
  • Write a message that adds context, not noise. The message should name the operation and the salient values in prose a human reading a log will understand, while the fields carry the same facts in a form code can act on.

Practice Exercises

  1. Insufficient-funds withdrawal. Write a checked InsufficientFundsException extends Exception carrying final balance and requested fields and a shortfall() method. Give an Account a withdraw(int) that throws it when the request exceeds the balance, and a main that catches the exception and prints the shortfall. Verify the balance is unchanged after a failed withdrawal.
  1. Wrap and chain. Write a ParseConfigException extends RuntimeException with a (String key, Throwable cause) constructor. In a loadPort(String key, String raw) method, parse raw with Integer.parseInt and, on NumberFormatException, throw your exception with the original as the cause. In main, catch it and print both getMessage() and the simple class name of getCause().
  1. A typed hierarchy with catch routing. Define a base ShippingException extends Exception with subtypes AddressInvalidException (carrying a field name) and CarrierUnavailableException. Write a ship(String scenario) that throws the appropriate subtype, and an attempt method whose catch blocks route each subtype to a different action -- printing the offending field for the address case and a generic message via the base catch otherwise. Confirm the specific catch precedes the base catch.