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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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
throwsthrough 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
@Transactionalrolls back by default only for RuntimeException and Error. A checked exception commits unless you setrollbackFor. - 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
- Checked or unchecked for InsufficientBalanceException? Why?
- What does try-with-resources do that finally does not?
- What happens to an exception thrown by close()?
- How does Spring decide whether to roll back?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.