Lesson · Exception Handling
Custom exceptions: domain language the compiler understands
15 min readCustom Exceptions
A domain exception names the failure, carries the data a caller needs to respond, and chooses its road deliberately: Exception when callers must decide, RuntimeException when the failure is a bug or business rule. Cause chaining keeps the original story.
From 'failed' to a decision
The difference between a generic failure and a domain exception is what the catch site can do with it:
throw new IllegalStateException("payment failed"); // catch site: log it. That is all the information allows. throw new InsufficientFundsException(required, available); // catch site: catch (InsufficientFundsException e) { offerTopUp(e.required() - e.available()); // a decision the type made possible }
Predict: which of the two lets a caller recover? The second: the type names the condition, and its fields carry the numbers recovery needs. A custom exception is an API: the catch block is its client, and its fields are the payload.
Designing one
Four decisions, each with a default:
| Decision | Guidance |
|---|---|
| Which road | Extend Exception when every caller must decide (checked); extend RuntimeException when the failure is a bug or a business rule the caller usually cannot preempt |
| Which constructors | At minimum (String message) and (String message, Throwable cause); call super(...) so the message and cause are real |
| Which fields | Only data a catch site will act on: amounts, ids, codes; skip fields that only restate the message |
| Which name | A noun phrase ending in Exception describing the condition: InsufficientFundsException, not PaymentProblem or Error42 |
- Prefer standard exceptions when they fit:
IllegalArgumentExceptionandIllegalStateExceptionalready say argument bug and call-order bug; invent a type only when the domain has vocabulary worth carrying. - Messages are data: build them in the constructor from the fields, keep them non-null, and make them self-contained (the log line may travel alone).
- No logic in constructors: assign only; validation or side effects belong elsewhere.
The catch site is the customer. Every design question (road, fields, constructors) is answered by asking what a catch block can usefully do with this type, not what the thrower finds convenient.
Translating with the cause attached
At boundaries, low-level failures become domain failures, and the original exception rides along as the cause:
catch (IOException e) { throw new ConfigException("config unreadable", e); // cause preserved } // the catch site sees both stories: // caught: config unreadable | cause: settings.xml missing
super(message, cause)stores the original;getCause()returns it and printStackTrace shows theCaused by:chain.- The callers now speak domain, while the diagnostics keep the file name that the domain layer never knew.
- This is the standard translation move from the checked-vs-unchecked lesson, now with a named home: the domain exception.
- One rule: never drop the cause when translating; a fresh exception without
eerases the evidence.
The verified demo carries both styles: an unchecked domain rule (InsufficientFundsException with needs 80.0, has 50.0 and a computed shortfall: 30.0) and a checked translation (config unreadable with cause settings.xml missing).
Domain language · what catch blocks can do
pick a sceneStandard exceptions say 'argument bug' or 'wrong state' well. When they would only ever be logged, they are enough.
The two outputs were produced by running the lesson's demo with javac 21; the messages and cause text are real.
The custom-exception playbook
Inventing a type, in order:
- Ask first: do the standard exceptions already say this? Argument bug, null, wrong state, unsupported operation: they do.
- If the domain has a name for the condition, create one type for it, with the fields a catch site will use.
- Choose the road by agency: callers must decide (checked) or this is a bug or rule they cannot preempt (unchecked).
- Provide message and message-plus-cause constructors; delegate with
superand keep messages complete. - At translation boundaries, wrap with the domain type and attach the original as cause; never translate without it.
A small vocabulary of well-shaped exceptions beats a hierarchy of clever ones. One type per actionable condition, carrying real data, keeps every catch block a readable decision.
A custom exception is an API for catch blocks
Name the condition in the type, carry the fields recovery needs, provide the message and message-plus-cause constructors, and choose Exception or RuntimeException by whether callers must decide. When translating at boundaries, wrap with the domain type and keep the cause attached so diagnostics and domain language travel together.
Interview angles
When does a custom exception earn its existence?+
When the domain has a named condition a catch site can act on and standard exceptions do not carry that meaning or data: insufficient funds, invalid coupon, version mismatch.
The test is recoverability plus vocabulary. A type whose catch block can only log has not earned its file; IllegalStateException("payment failed") was already enough for logging, and a domain type with required/available fields enables the top-up offer.
throw new InsufficientFundsException(required, available); // typed payload
Common misconception: That every project layer needs its own exception for every failure. A small vocabulary of actionable types beats a mirrored taxonomy of every layer.
Follow-up: What is the smell of an exception type that never gets a distinct catch block?
Which constructors should every custom exception provide?+
At least (String message) and (String message, Throwable cause), each delegating with super; some add () and the cause-only form for completeness.
The pair covers the two real scenarios: a fresh condition (message) and a translation (message plus the original). Missing the cause constructor is why translations end up dropping evidence.
ConfigException(String message, Throwable cause) { super(message, cause); }
Common misconception: That constructors should 'do work'. They assign; validation and side effects belong to the code that decides to throw.
Follow-up: What does a fixed serialVersionUID affect, and is it required?
Exception or RuntimeException for a new domain type?+
Exception (checked) when the caller must decide and can: parsing user input, external calls. RuntimeException when the failure is a bug or a rule the caller cannot preempt: wrong state, invariant violation.
The decision shows up in signatures: a checked type adds throws obligations and lambda friction; an unchecked one travels silently and surfaces where it surfaces. Choose by who acts, as in the checked-vs-unchecked lesson, applied to your own vocabulary.
class InsufficientFundsException extends RuntimeException { ... } // rule the caller cannot pre-check away
Common misconception: That business-rule failures must be checked. Many teams make them unchecked precisely because callers usually cannot do anything useful where the call happens.
Follow-up: When would a payment library reasonably make insufficient funds checked instead?
How does cause chaining work behind the scenes?+
The (message, cause) constructor stores the original throwable; getCause() returns it, printStackTrace renders the Caused by: chain, and nested causes nest indefinitely.
Chains are how diagnostics survive translation: the domain layer reports 'config unreadable' while the report still shows 'settings.xml missing' underneath. Breaking the chain (throwing without the cause) is the classic way to make a production report useless.
throw new ConfigException("config unreadable", e); // e becomes getCause()
Common misconception: That wrapping duplicates logging. The reporter logs once, at the boundary, and the single log line carries the whole chain.
Follow-up: What does printStackTrace show for a two-level translation?
What belongs in a custom exception's message?+
The facts a reader needs without the stack: what operation failed, the relevant identifiers and values, kept stable enough to grep and log.
Because messages are built from the fields in the constructor, the log line and the catch site's data never disagree. Keep them free of padding like 'Error occurred:' and free of secrets: logs travel.
super("needs " + required + ", has " + available);
Common misconception: That messages can wait for the logger. The thrower knows the facts; the logger only knows the message, wherever it is printed or wrapped.
Follow-up: Which two audiences read the message, sometimes years later?