The Real Names#
A custom exception is a class that extends Exception (checked) or RuntimeException (unchecked), carrying a clear name and any extra
data the handler needs.
class InsufficientCreditsException extends Exception {
// checked: callers must plan for it
private final int needed, available;
InsufficientCreditsException(int needed, int available) {
super("Need " + needed + " credits, have " + available); // the message
this.needed = needed;
this.available = available;
}
int shortBy() {
return needed - available;
} // extra data for the handler
}
static int credits = 3;
static void askAi(int cost) throws InsufficientCreditsException {
if (cost > credits) throw new InsufficientCreditsException(cost, credits);
credits -= cost;
}
try {
askAi(2);
askAi(5);
} catch (InsufficientCreditsException e) {
System.out.println(e.getMessage() + " (short by " + e.shortBy() + ")");
}
// Need 5 credits, have 1 (short by 4)The handler can now show "Buy 4 more credits" instead of a generic error.
Wrapping (chaining) exceptions#
Low-level exceptions should be translated into ones that make sense at your level — keeping the original as the cause:
class QuizStorageException extends RuntimeException {
QuizStorageException(String msg, Throwable cause) {
super(msg, cause);
} // pass the cause along
}
static void loadQuiz(String path) {
try {
/* ... reading the file throws ... */ throw new FileNotFoundException(
path + " (No such file or directory)"
);
} catch (IOException e) {
throw new QuizStorageException("could not load quiz " + path, e);
}
}
// could not load quiz biology.json | cause: java.io.FileNotFoundException: biology.json (No such file or directory)A stack trace of a wrapped exception prints both, with a Caused by: section — so the root cause is never lost. Never wrap without passing
the cause.
Good practice — the rules interviewers look for#
Fail fast: check arguments at the start of a method and throw immediately (
IllegalArgumentException,Objects.requireNonNull(x)), instead of failing mysteriously ten calls later.Don't use exceptions for normal control flow. They're slow — creating one captures the whole stack trace. Measured on this Mac:
Output 100,000 failed Integer.parseInt calls caught as exceptions: 101 ms 100,000 equivalent up-front checks: 4 msCheck first (
if (s.isEmpty() || !Character.isDigit(...))) when failure is common and expected.Catch at the level that can do something useful: retry, use a default, show a message, or return an HTTP status. Everything else lets it propagate.
Never swallow (Ch 2). Always keep the cause when wrapping.
Include useful context in messages: which quiz, which student, what value — not just "error".
Use the standard types when they fit:
IllegalArgumentException(bad argument),IllegalStateException(object in the wrong state for this call),UnsupportedOperationException,NoSuchElementException.
Check yourself
4 questionsWhen would you make a custom exception checked vs unchecked?
Show answerHide answer
Checked for expected, recoverable conditions callers should plan for (insufficient credits); unchecked for programming errors or failures callers can't reasonably handle.
Why pass the original exception when wrapping?
Show answerHide answer
So the root cause and its stack trace are preserved (shown as "Caused by").
Why shouldn't exceptions be used for normal control flow?
Show answerHide answer
They're expensive (they capture the stack trace) and they obscure the normal logic; measured ~25× slower than a simple check here.
What does "fail fast" mean?
Show answerHide answer
Detect invalid input or state as early as possible and throw immediately, rather than failing confusingly later.