Skip to the page

Types, errors and modern syntax · core

Exceptions and try-with-resources

Checked exceptions force callers to handle errors; unchecked ones do not. Close resources with try-with-resources, never with a hand-written finally.

The notes

What you must know

  • Checked exceptions: the compiler forces catch or throws. Unchecked exceptions (RuntimeException) are for programming errors and most business errors.
  • Checked exceptions spread throws through every layer and do not fit lambdas and streams.
  • A common design: an unchecked business exception hierarchy with error codes, mapped in one global handler to a 4xx response.
  • Spring's @Transactional rolls back by default only for RuntimeException and Error. A checked exception commits unless you set rollbackFor.
  • Errors such as OutOfMemoryError and StackOverflowError are not for application code to catch. Never swallow an exception; wrap it with the cause.
  • A result type (a sealed interface with Success and Declined records) is a good fit for expected outcomes.
  • try-with-resources closes resources in reverse order, even on exceptions, and attaches exceptions from close as suppressed (getSuppressed()).
  • Hand-written finally can fail twice: a null reader throws NullPointerException in finally and hides the real cause. Works with anything that implements AutoCloseable. Since Java 18 the default charset is UTF-8 everywhere, but pass the charset anyway to show intent.

The red pen

Common traps: mistake → fix

  • Mistake: Checked is always better because it forces handling

    Fix: it spreads through code and breaks lambdas.

  • Mistake: @Transactional rolls back on every exception

    Fix: not on checked exceptions by default.

  • Mistake: finally { reader.close(); } is safe

    Fix: it can throw NullPointerException or hide the original exception.

Easy to hard

Questions interviewers ask, easy to hard

  1. Checked or unchecked for InsufficientBalanceException? Why?
  2. What does try-with-resources do that finally does not?
  3. What happens to an exception thrown by close()?
  4. How does Spring decide whether to roll back?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview