An exception aborts the current path and pops the stack until a matching catch, or it kills the thread (and may kill the process if it is the last non-daemon thread). It is not a second return value. Do not use exceptions for ordinary control flow.
Optional); loop exit; validating a form field you will report next to the input.Definition: a checked exception is a Throwable that is not RuntimeException or Error. The compiler requires it to be caught or declared. Unchecked exceptions do not need a throws clause.
| Type | Kind | Use |
|---|---|---|
Error | unchecked | JVM-level (OutOfMemoryError, StackOverflowError). Do not catch unless you are a container and you rethrow. |
RuntimeException | unchecked | Programming mistakes and unrecoverable-at-this-layer faults: NPE, IAE, ISE, CCE. |
Other Exception | checked | Recoverable conditions the caller must acknowledge: IOException, SQLException, InterruptedException. |
IllegalArgumentException — bad argument (null, negative, empty) the caller could have avoided.IllegalStateException — this object is not in a state that allows the call (closed, not started).NullPointerException — prefer Objects.requireNonNull so the name of the argument appears.UnsupportedOperationException — this implementation does not support the optional operation (immutable lists’ add).InterruptedException — you were asked to stop waiting. Restore the interrupt flag if you cannot propagate: Thread.currentThread().interrupt().There is no single religion, but professionals are consistent inside a codebase:
throws IOException through twenty domain layers. Catch at the boundary and throw a domain unchecked or a dedicated checked type.catch (Exception e) {}.// Boundary translation
try (InputStream in = Files.newInputStream(path)) {
return parse(in);
} catch (IOException e) {
throw new DataAccessException("read " + path, e); // keep the cause
}
Always pass the cause. An empty catch that logs nothing is a production defect.
try {
work();
} catch (IOException e) {
throw new DataAccessException("work", e);
} finally {
// runs on success, failure, and return — unless VM death / infinite hang
}
catch (Exception e) first swallows everything.catch (IOException | SQLException e) — e is effectively final.finally that throws hides the original exception. This is why handwritten close is dangerous.return in finally overrides a previous return or exception — never do this.Any AutoCloseable (including Closeable) can be declared in try (...). Resources close in reverse order, even if the body or a previous close throws. Secondary failures are suppressed on the primary exception (getSuppressed()).
try (var in = Files.newBufferedReader(path);
var out = Files.newBufferedWriter(dest)) {
in.transferTo(out); // Java 10+ Reader.transferTo
}
When not to use TWR: you must return an open stream to the caller (document who closes). Then the caller should TWR.
AccountClosedException, not MyException.public final class AccountClosedException extends IllegalStateException {
public AccountClosedException(String accountId) {
super("account closed: " + accountId);
}
}
assert cond : message; is for internal invariants and is off unless -ea. Never use assert to validate public arguments or any check that must run in production. That is IllegalArgumentException / Objects.requireNonNull.
catch (Exception e) { } or logging and continuing as if success.Exception around a whole request and returning 200.throw new RuntimeException("fail") without e.InterruptedException and not restoring the interrupt flag.printStackTrace() to stdout instead of a logger with context.throws Exception on every method).// Incorrect
} catch (InterruptedException e) {
return; // thread stays interrupted-unaware
}
// Correct
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted", e);
}
~ Good luck with your revision! ~