Easy java core-java

What is the difference between checked and unchecked exceptions?

The 30 second answer

Checked exceptions, like IOException, must be caught or declared with throws, and the compiler enforces it; they're for problems the caller can reasonably recover from. Unchecked exceptions are RuntimeException and its subclasses, like NullPointerException or IllegalArgumentException; they usually mean a bug or bad input, and the compiler doesn't force handling. Errors like OutOfMemoryError are serious JVM problems that an application normally shouldn't catch.

<!-- level: 1 --> <!-- must_know: true -->

Throwable
├── Error                  (OutOfMemoryError, StackOverflowError) – don't catch
└── Exception              checked (IOException, SQLException)
    └── RuntimeException   unchecked (NullPointerException, IllegalArgumentException)
  • Checked: every Exception that is not a RuntimeException. The Java Language Specification requires a method to catch it or declare it in throws.
  • Unchecked: RuntimeException, Error and their subclasses. No compile-time requirement.
  • The Java tutorial's guideline: "If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception."

Good habits interviewers like: never swallow an exception with an empty catch, wrap low-level exceptions with a cause (new OrderException("save failed", e)), and log an exception once where it is handled. Spring rolls back @Transactional methods for unchecked exceptions by default but not checked ones, which connects this question to What does @Transactional do?.

Sources (2)
  1. Java Language Specification, chapter 11: Exceptionsdocs.oracle.com
  2. Java tutorial: Unchecked exceptions, the controversydocs.oracle.com