Exceptions
An exception is an object describing something that went wrong, thrown at the point of failure and caught somewhere up the call stack. It separates the code that detects a problem from the code that decides what to do about it.
Detailed Explanation
Before exceptions, error reporting rode along with the return value. A C function returns -1 and sets a global errno. Every caller must check, and any caller who forgets carries on with garbage. Worse, the return channel is already busy: a function that computes a value has nowhere left to say "I failed".
Exceptions give failure its own channel. You throw an object at the point where the problem is detected, and the JVM abandons the current method, then its caller, then its caller, until it finds a catch block whose type matches. This walk is called stack unwinding. Local variables of each abandoned frame become garbage; finally blocks on the way out still run.
The type hierarchy is worth learning properly, because everything else follows from it. Throwable is the root. It has two children. Error means the JVM itself is in trouble — OutOfMemoryError, StackOverflowError — and you should not catch it, because there is nothing useful you can do. Exception means the application has a problem. Under Exception sits RuntimeException, and the presence or absence of that ancestor decides whether the compiler forces you to handle it.
Three blocks do the work. try marks the region being guarded. catch handles one or more types, most specific first, since the first matching clause wins. finally runs on every exit path: normal completion, a caught exception, an uncaught one passing through, even a return inside the try. Since Java 7, multi-catch lets one clause handle several unrelated types with |, and try-with-resources replaces most hand-written finally blocks for closing things.
Two habits separate usable error handling from the frustrating kind. First, chain the cause. When you catch a low-level failure and rethrow something meaningful to your layer, pass the original as the cause: throw new ConfigException("cannot read config", e). The printed trace then shows both the business-level message and the socket timeout underneath it. Second, never write an empty catch block. Swallowing an exception deletes the only evidence of the failure and turns a five-minute fix into a day of guessing.
When should you throw one? When the method cannot do what its name promises. parsePort("abc") cannot return a port, so it throws. Do not use exceptions for expected outcomes that the caller will hit constantly. "This cache key is absent" is not exceptional; return Optional instead.
That advice is partly about cost. Throwing is not free. The expensive part is not the unwinding, it is fillInStackTrace, which walks and records every frame at construction time. A deep stack makes a single throw cost microseconds, thousands of times more than a comparison. Using exceptions as a loop exit will show up in a profiler. If you have a genuine hot path with a pre-allocated exception, you can override fillInStackTrace to skip capture, but that is a last resort, and the JVM already does this for some internal cases.
Code Examples
public class ExceptionFlow {
// A domain exception carries data the caller can actually act on,
// not just a string.
static class InsufficientFundsException extends RuntimeException {
private final long shortfallInCents;
InsufficientFundsException(long shortfallInCents) {
super("short by " + shortfallInCents + " cents");
this.shortfallInCents = shortfallInCents;
}
long shortfallInCents() {
return shortfallInCents;
}
}
static void withdraw(long balanceInCents, long amountInCents) {
if (amountInCents > balanceInCents) {
// Throwing abandons this method immediately; nothing below runs.
throw new InsufficientFundsException(amountInCents - balanceInCents);
}
}
public static void main(String[] args) {
try {
withdraw(500, 900);
System.out.println("never reached");
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage()); // prints: short by 400 cents
System.out.println(e.shortfallInCents()); // prints: 400
} finally {
// Runs on every exit path, including an uncaught throw passing through.
System.out.println("audit record written"); // prints: audit record written
}
}
}import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
class ConfigLoader {
static class ConfigException extends RuntimeException {
ConfigException(String message, Throwable cause) {
super(message, cause); // the cause keeps the original stack trace
}
}
static String load(Path path) {
try {
return Files.readString(path);
} catch (IOException | SecurityException e) {
// Multi-catch (Java 7+): one clause, two unrelated types.
// Wrap and rethrow with context. Never swallow silently.
throw new ConfigException("cannot read config at " + path, e);
}
}
public static void main(String[] args) {
try {
load(Path.of("does-not-exist.yaml"));
} catch (ConfigException e) {
System.out.println(e.getMessage());
System.out.println(e.getCause().getClass().getSimpleName());
// prints: java.nio.file.NoSuchFileException as the cause type
}
}
}Common Gotchas
A return inside finally discards the exception
if `finally` executes its own `return` or `throw`, the exception travelling out of the `try` is dropped without trace. Never put a `return` in a `finally` block.
Catching Exception catches too much
it also catches `RuntimeException`, so a `NullPointerException` in your own handler code gets logged as if it were the expected failure. Catch the narrowest type you can actually handle.
Exceptions are slow enough to matter in loops
stack trace capture dominates the cost and grows with stack depth. Do not use a throw to signal "not found" in code that runs millions of times.
The stack trace records where the exception was constructed, not where it was thrown
they are almost always the same line, but a pre-allocated or reused exception object will report a misleading origin.