Exceptions · interview question
Explain checked vs unchecked exceptions in Java. When would you use each in your own API?
0 words · aim for 40+
Answer and explanation
Correct answer
Checked exceptions are subclasses of Exception but not RuntimeException, like IOException. The compiler forces callers to catch or declare them. Unchecked exceptions extend RuntimeException, like IllegalArgumentException and NullPointerException, and don't need to be declared.
Use checked exceptions for recoverable conditions the caller can reasonably handle, such as a missing file the user can pick again. Use unchecked exceptions for programming errors and precondition violations (bad arguments, illegal state) and when the caller can't do anything useful. Many modern APIs lean unchecked because checked exceptions don't compose well with lambdas and streams. Either way, document what you throw, keep the cause when wrapping (new ServiceException("msg", e)), and don't swallow exceptions.
Key points:
- Checked exceptions must be caught or declared; unchecked don't
- Unchecked exceptions extend RuntimeException
- Checked: recoverable conditions the caller can handle
- Unchecked: programming errors and precondition violations
- Preserve the cause when wrapping exceptions
Why
Mentioning lambdas/streams friction and exception chaining shows real-world experience.
References
- The Java Tutorials: Exceptions
- Joshua Bloch, Effective Java, 3rd ed. (2018)
Test yourself on Exceptions
A free test with instant, explained results. No account needed.
More Exceptions questions
- Why can overusing exception wrapping become a problem in practice?
- Why wrap an exception with the original cause instead of replacing it completely?
- Which of the following is NOT a recommended practice for exception handling?
- Which method is used to retrieve the original cause of a chained exception?
- What exception type should you throw when encountering a database connection error in an e-commerce application?
- How would you explain a key reason to use exception wrapping in a Java interview?