The exception hierarchy
Throwableis the root.Error: serious JVM problems you normally don't catch (OutOfMemoryError,StackOverflowError).Exception: problems a program can handle.RuntimeExceptionand its subclasses are unchecked (NullPointerException,IllegalArgumentException,IndexOutOfBoundsException).- Every other
Exceptionis checked (IOException,SQLException): the compiler forces you to catch it or declare it withthrows.
Rule of thumb: checked exceptions for conditions a caller can reasonably recover from (file missing); unchecked for programming errors (null argument, bad index).
try, catch, finally and try-with-resources
try {int n = Integer.parseInt(input);process(n);} catch (NumberFormatException e) { // most specific firstlog.warn("not a number: {}", input);} catch (IOException | SQLException e) { // multi-catch (Java 7+)throw new ServiceException("processing failed", e); // keep the cause} finally {metrics.done(); // runs whether or not something was thrown}
try-with-resources closes anything that implements AutoCloseable, in reverse order, even if an exception is thrown. Exceptions thrown while closing are attached as suppressed to the main one instead of hiding it.
try (var in = Files.newBufferedReader(path);var out = Files.newBufferedWriter(copy)) {in.transferTo(out);} // out.close(), then in.close(), automatically
finally edge cases
finallyruns afterreturnis evaluated but before the method actually returns.- A
returninsidefinallyoverrides the try's return value and swallows any exception: never do it. finallydoesn't run if the JVM exits (System.exit) or the thread is killed.
static int f() {int x = 1;try { return x; } // the value 1 is saved herefinally { x = 2; } // changing x doesn't change the saved value}// f() returns 1
Custom exceptions and good practice
public class InsufficientFundsException extends Exception {private final long shortBy;public InsufficientFundsException(long shortBy) {super("Short by " + shortBy);this.shortBy = shortBy;}public long shortBy() { return shortBy; }}
- Catch the most specific type you can handle; don't catch
ExceptionorThrowableblindly. - Never swallow an exception silently. At least log it, or rethrow.
- When wrapping, pass the original as the cause so the stack trace survives.
- Don't use exceptions for normal control flow; they're slow and obscure intent.
- Fail fast: validate arguments early with
Objects.requireNonNullorIllegalArgumentException.
See it animated
Interview questions
Try answering out loud first, then open the model answer.
Q1Checked vs unchecked exceptions?beginner
Checked exceptions (subclasses of Exception but not RuntimeException) must be caught or declared with throws; the compiler enforces it. Unchecked ones (RuntimeException, Error) don't. Checked: recoverable external conditions; unchecked: programming bugs.
Q2throw vs throws?beginner
throw actually throws an exception object inside a method body. throws in a method signature declares which checked exceptions the method may let escape to its callers.
Q3Does finally always run?intermediate
Almost always: after normal completion, after a caught or uncaught exception, and after return/break. It doesn't run if the JVM halts (System.exit, a crash) or the thread dies abruptly.
Q4What is try-with-resources and what are suppressed exceptions?intermediate
A try statement that declares AutoCloseable resources and closes them automatically in reverse order. If the body throws and close() also throws, the close exception is attached to the main one via addSuppressed (readable with getSuppressed()) instead of replacing it.
Q5Can you catch multiple exceptions in one block?beginner
Yes, with multi-catch: catch (IOException | SQLException e). The types can't be subclasses of each other, and e is implicitly final.
Q6What does this return? try { return 1; } finally { return 2; }intermediate
2. A return in finally replaces the try block's return value (and would also swallow any exception), which is why returning from finally is considered a bug.
Q7Is it a good idea to catch Exception?intermediate
Rarely. It also catches programming errors you'd rather see fail fast, and hides what can actually go wrong. Catch specific types; a broad catch belongs only at a boundary (top of a request handler or thread) where you log and convert to an error response.
Quick check
0 of 4 answered