Interview Q&A · Java · 4 questions in this topic

Checked vs Unchecked Exceptions — Java Interview Q&A

All Java topics

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

Example.javajava
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

  1. 1No compile-time enforcement: code compiles even without handlers.
  2. 2Typical cause is a preventable bug rather than an external condition.
  3. 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

  1. 1Hierarchy: checked types extend Exception excluding RuntimeException; unchecked types extend RuntimeException or Error.
  2. 2Enforcement: checked failures are verified at compile time, unchecked failures are not.
  3. 3Typical causes: checked means environment or IO problems, unchecked means logic errors.
  4. 4Examples: checked includes IOException and SQLException; unchecked includes NullPointerException and ArithmeticException.

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits