Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 201 ยท Exceptions

Custom Exceptions

Learn to create custom exceptions in Java - checked or unchecked, the standard constructors, extra fields, exception hierarchies, chaining causes and exception translation.

The JDK's exceptions describe technical problems: a bad argument, a missing file, a null where an object was expected. Your application has problems of its own that no JDK class names: an order that can't ship because an item is out of stock, a withdrawal larger than the balance, a coupon that has expired. A custom exception gives such a problem a name, a place in a hierarchy, and room for the details a caller needs to react to it.

Writing an exception class takes only a few lines, but doing it well involves several decisions: checked or unchecked, which constructors, what extra data, how to keep the original cause when one exception leads to another. This lesson walks through all of them, then shows exception translation, the technique that keeps low-level details like SQLException from leaking out of your classes.

When a custom exception is worth it

Create your own exception class when at least one of these is true:

  • Callers need to catch this problem specifically. If the checkout code must react differently to "out of stock" than to "payment declined," those need to be different types. Catching by message text (if (e.getMessage().contains("stock"))) is fragile and breaks when someone rewords a message.
  • The problem carries data. An InsufficientFundsException that exposes the balance and the requested amount lets the caller say "you can withdraw at most 40.00" without parsing strings.
  • It's a concept from your domain, and the name makes stack traces and logs self-explanatory.

When none of these apply, use a standard exception (Throwing Exceptions has the list). IllegalArgumentException("quantity must be positive, was -3") is perfectly clear; an InvalidQuantityException adds a class without adding meaning.

Defining an exception class

An exception class is an ordinary class that extends Exception (for a checked exception) or RuntimeException (for an unchecked one). By convention, its name ends in Exception.

Java
public class OutOfStockException extends RuntimeException {
    public OutOfStockException(String message) {
        super(message);
    }
}

Passing the message to super(...) stores it in Throwable, so getMessage(), toString() and stack traces all show it. Don't add your own message field; Throwable already has one.

Checked or unchecked?

Apply the rule from the previous lesson: make it checked (extend Exception) only if a typical caller can recover and you want the compiler to make sure they think about it. Make it unchecked (extend RuntimeException) for programming errors, violated preconditions, and problems most callers will just let propagate to a central handler. Modern Java code, especially in web frameworks, leans strongly toward unchecked.

Never extend Throwable or Error directly. Error is reserved for JVM-level failures, and code that catches Exception won't see a direct Throwable subclass.

The standard constructors

Most exception classes in the JDK offer four constructors, and yours should offer at least the ones you need, all delegating to super:

Java
public class ConfigException extends Exception {
    public ConfigException() { super(); }
    public ConfigException(String message) { super(message); }
    public ConfigException(String message, Throwable cause) { super(message, cause); }
    public ConfigException(Throwable cause) { super(cause); }
}

The (message, cause) constructor is the important one: it's how you chain exceptions, below. If your exception can ever be caused by another one, provide it.

Throwable implements Serializable, so with all lint warnings enabled (javac -Xlint:all), the compiler suggests a serialVersionUID for exception classes: private static final long serialVersionUID = 1L;. It only matters if exceptions are serialized (old RMI-style systems); many teams add it to keep builds warning-free. See Serialization.

Adding fields for the details

Here's a bank account whose withdraw method throws a checked exception carrying the numbers a caller needs:

Java A checked exception with extra fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Some design points:

  • The fields are final and set in the constructor. An exception describes something that already happened; it shouldn't change afterwards.
  • The message is built from the fields, so it's always consistent with them, and the caller doesn't have to assemble it.
  • The caller uses the fields, not the message, to make decisions (shortfallCents()). Messages are for humans; fields are for code.
  • An invalid amount is still a standard IllegalArgumentException. Not every problem in the class needs a custom type: a negative amount is a bug in the caller, while insufficient funds is a normal business situation.

Records can't be exceptions, by the way: a record can't extend a class, and exceptions must extend Throwable.

Building an exception hierarchy

In a larger module, define a base exception for the module and specific subclasses beneath it. Callers can then choose how precise to be: catch one specific subclass, or catch the base type to handle everything from your module in one place.

Java A small exception hierarchy with error codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The ErrorCode enum is a common addition in services and APIs: the code is stable and machine-readable (a web API can return it as JSON), while the message can be reworded freely. Keep hierarchies shallow, though. Two levels (a module base and a handful of specific types) cover almost every need; a deep tree of exception classes is rarely worth maintaining.

An exception base class can also be sealed: sealed class OrderException extends RuntimeException permits OutOfStockException, CouponException. Then a switch over a caught OrderException with one case per subtype is exhaustive, and adding a new subtype shows you every handler that needs updating.

Chaining: keeping the cause

Often your exception is caused by another one: a configuration can't be loaded because a file couldn't be read. If you throw a new exception and drop the original, the stack trace that explained the real problem is gone. Instead, pass the original as the cause:

Java
catch (IOException e) {
    throw new ConfigException("cannot load settings from " + path, e);   // e becomes the cause
}

The new exception says what failed at your level; the cause says why, at the level below. getCause() returns it, and stack traces print the whole chain:

Java Chained exceptions and the Caused by section

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The printed trace starts with Main$ConfigException (the $ marks a nested class) and ends with a Caused by: section, followed by a line like ... 6 more. That means the remaining frames of the cause are the same as the frames already printed above it, so Java leaves them out. (The frames below Main.main belong to the launcher that runs single-file programs; in an application started from a JAR, main is the last frame.) In real traces, chains can be several levels deep (Caused by: ... Caused by: ...); the last Caused by is usually the root of the problem, so read it first.

To find that root cause in code, follow getCause() until it returns null:

Java
static Throwable rootCause(Throwable t) {
    Throwable current = t;
    while (current.getCause() != null && current.getCause() != current) {
        current = current.getCause();
    }
    return current;
}

If an exception class has no constructor with a cause parameter, you can attach one afterwards with initCause(cause), once, before the exception is thrown. Providing the constructor is cleaner.

Exception translation

Chaining makes a powerful technique possible. Imagine a UserRepository that stores users in a database. Its methods could declare throws SQLException, but then every caller, even the web layer, would depend on JDBC details. Switch the storage to files or a REST service and every caller's catch blocks change.

Exception translation means each layer catches the low-level exceptions it knows about and throws an exception that fits its own abstraction, with the original attached as the cause:

Java Translating low-level exceptions at a layer boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The caller (think of a web controller) handles two meaningful situations: the user doesn't exist (404) or the storage is down (503). It knows nothing about IOException, yet nothing is lost: logs still see the original problem through the cause. This is exactly how frameworks like Spring work: they translate SQLExceptions into their own unchecked data-access exceptions (Advanced Java covers this).

Two mistakes to avoid when translating:

  • Losing the cause: throw new RepositoryException("could not load user") without e throws away the only clue to what happened.
  • Translating too much: wrapping every exception at every method creates traces with ten Caused by levels that all say the same thing. Translate at layer boundaries (storage to service, service to web), not in every method.

Advanced: cheaper exceptions

Creating an exception captures the current stack trace, which costs time proportional to the stack depth. For ordinary errors, that cost is irrelevant. If you ever have an exception that's thrown very frequently and whose trace nobody reads, Throwable has a protected constructor that skips it:

Java
class StopParsing extends RuntimeException {
    StopParsing() {
        super(null, null, false, false);   // no suppression, no stack trace
    }
}

The last two arguments disable suppressed exceptions and the stack trace. Use this rarely and deliberately; in almost all code, a cheaper exception is a sign that the logic should use a return value or Optional instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which superclass makes a custom exception unchecked?

    Subclasses of RuntimeException are unchecked. Extending Exception makes it checked, Error is reserved for JVM problems, and Throwable shouldn't be extended directly.
  2. 2. Why should a caller check e.shortfallCents() instead of parsing e.getMessage()?

    Exception messages are documentation that can change at any time. Typed fields and methods give callers reliable data to make decisions with.
  3. 3. What does new ConfigException("cannot load", e) do with e?

    The (message, cause) constructor chains the exceptions. The new exception keeps its own message and stack trace, and the original is preserved as its cause.
  4. 4. A service layer catches SQLException from its database code. What does exception translation recommend?

    Translation keeps storage details out of the service's interface while preserving the original exception as the cause for logs and debugging.
  5. 5. In a long stack trace with three Caused by sections, where is the root of the problem usually described?

    Each Caused by is the reason for the exception above it, so the last one in the chain is the original problem. Read it first, then work upward.

Summary

  • Create a custom exception when callers need to catch the problem specifically, when it carries data, or when it names a domain concept; otherwise use a standard exception.
  • Extend RuntimeException for unchecked or Exception for checked; never Throwable or Error. End the name with Exception.
  • Pass the message (and cause) to super; provide a (String message, Throwable cause) constructor whenever chaining is possible.
  • Put extra details in final fields with accessors, build the message from them, and let code decide based on fields, not message text.
  • A shallow hierarchy (a module base class plus specific subclasses, optionally with an error-code enum or a sealed base) lets callers choose how precise to be.
  • Chain exceptions instead of dropping them; read the last Caused by first, or walk getCause() in code.
  • Exception translation converts low-level exceptions into your layer's own types at layer boundaries, keeping the original as the cause.

Next: try-with-resources, where Java closes files, connections and other resources for you, even when exceptions fly.