Interview Q&A · Java · 4 questions in this topic
Checked vs Unchecked Exceptions — Java Interview Q&A
The compile-time divide between failures you must declare and failures that signal programming bugs. Part of Exception Handling · 294 questions in the Java bank.
What are checked exceptions?
Answer
Checked exceptions are failure types the compiler forces you to acknowledge, either by catching them or by declaring them with throws. They model recoverable external conditions such as IOException, SQLException, and ClassNotFoundException. RuntimeException, Error, and their subclasses are excluded from this enforcement.
Example
void load() throws java.io.IOException { java.nio.file.Files.readAllLines(java.nio.file.Path.of("app.txt")); }
What are unchecked exceptions?
Answer
Unchecked exceptions are RuntimeException and its subclasses, plus Error and its subclasses, for which the compiler requires no catch or throws declaration. They usually signal programming bugs such as NullPointerException, ArithmeticException, and IndexOutOfBoundsException. Because they can arise at many points, the language leaves handling them to the judgment of the programmer rather than enforcing it.
Key points
- 1No compile-time enforcement: code compiles even without handlers.
- 2Typical cause is a preventable bug rather than an external condition.
- 3Examples include NullPointerException, IllegalArgumentException, and IllegalStateException.
Differences between checked and unchecked exceptions.
Answer
Checked exceptions must be caught or declared, while unchecked exceptions compile without any handler or declaration. Checked exceptions usually represent external conditions the program should anticipate and recover from, while unchecked exceptions usually reflect bugs in the code itself. Their hierarchies differ as well, with checked types extending Exception directly and unchecked types living under RuntimeException or Error.
Key points
- 1Hierarchy: checked types extend Exception excluding RuntimeException; unchecked types extend RuntimeException or Error.
- 2Enforcement: checked failures are verified at compile time, unchecked failures are not.
- 3Typical causes: checked means environment or IO problems, unchecked means logic errors.
- 4Examples: checked includes IOException and SQLException; unchecked includes NullPointerException and ArithmeticException.
Can you catch a checked exception that can never be thrown?
Answer
No, the compiler rejects a catch for a checked type that the try body cannot possibly throw. For example, catching IOException around code with no IO calls fails with an exception never thrown error. Catching Exception, Throwable, or any unchecked type remains legal because an unchecked subtype could still arise.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission