Exceptions: Checked vs Unchecked and Best Practices
Java exceptions are split into checked exceptions the compiler forces you to handle and unchecked runtime exceptions. Interviewers ask about the hierarchy, try-with-resources, finally, and how exceptions should be handled in a Spring Boot service.
What you will learn
- Draw the Throwable hierarchy
- Compare checked and unchecked exceptions
- Use try-with-resources and multi-catch
- Create meaningful custom exceptions
Key concepts
Hierarchy
Throwable → Error (OutOfMemoryError, StackOverflowError: do not catch) and Exception. Exception → checked exceptions (IOException, SQLException) and RuntimeException (NullPointerException, IllegalArgumentException), which are unchecked.
Checked
Must be caught or declared with throws. Meant for recoverable conditions the caller should think about.
try-with-resources
Resources that implement AutoCloseable are closed automatically in reverse order, even on exceptions. Exceptions from close are added as suppressed exceptions.
Step by step
Good practice
- Never swallow exceptions with an empty catch
- Catch specific types, not Exception, unless at the top boundary
- Wrap low-level exceptions with context and keep the cause: new OrderFailedException("order " + id, e)
- In Spring services, throw unchecked domain exceptions and map them to HTTP in @RestControllerAdvice
- Do not use exceptions for normal control flow
Examples
try-with-resources and a custom exception
public class OrderNotFoundException extends RuntimeException {
public OrderNotFoundException(long id) {
super("Order " + id + " not found");
}
}
try (var conn = dataSource.getConnection();
var ps = conn.prepareStatement("SELECT total FROM orders WHERE id = ?")) {
ps.setLong(1, id);
try (var rs = ps.executeQuery()) {
if (!rs.next()) throw new OrderNotFoundException(id);
return rs.getBigDecimal("total");
}
} catch (SQLException e) {
throw new DataAccessFailure("Reading order " + id, e);
}Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Predict what is returned when both try and finally have a return statement.
- Convert a method full of checked exceptions into one that throws a single domain exception.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Does finally always run?
Almost always: after try, after catch, even after return. It does not run if the JVM exits (System.exit), the thread is killed, or the machine crashes. A return in finally overrides the try's return and swallows exceptions, so avoid it.
throw vs throws?
throw raises an exception object inside a method. throws in the method signature declares which checked exceptions it may pass to the caller.
Why do Spring and most modern code prefer unchecked exceptions?
Checked exceptions leak implementation details through every layer and lead to empty catches. Unchecked domain exceptions handled once at the boundary keep code clean; Spring also uses unchecked exceptions to roll back @Transactional by default.
Summary
Errors are fatal, checked exceptions must be handled or declared, runtime exceptions are unchecked. Close resources with try-with-resources, keep causes, and handle exceptions once at the boundary.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus