c2cedge
C, Java & Python · C — Java Essentials

Java: Exceptions & Error Handling

Checked vs unchecked, try-catch-finally, throw vs throws — exception handling is both a daily skill and a reliable interview topic.

Test weight: High (Java)Skill: Robust codeDifficulty: Medium

Java separates errors into exceptions you must handle and ones you needn't. Checked exceptions are checked at compile time — you must catch or declare them. Unchecked exceptions (subclasses of RuntimeException) occur at runtime and aren't forced on you. try/catch/finally handles them; throw raises one and throws declares it.

Checked vs unchecked, and finally

Checked (e.g. IOException): the compiler forces you to handle or declare them. Unchecked (e.g. NullPointerException, ArrayIndexOutOfBounds): programming errors at runtime, not forced. A finally block always runs — whether or not an exception occurred — ideal for cleanup.

try / catch / finally
try {
    int x = arr[10];          // may throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("bad index");
} finally {
    System.out.println("always runs");  // cleanup
}
⚡ The edge
  • Checked exceptions must be caught or declared with throws; unchecked ones (RuntimeException) needn't be. Checked = recoverable external problems (file/IO); unchecked = bugs (null, bad index).
  • The finally block always executes — after try or catch, even on a return — so it's where you release resources. throw raises an exception object; throws in a method signature declares what it might throw.
Worked example
What is the difference between checked and unchecked exceptions?
  1. Checked exceptions are verified at compile time — the compiler forces you to handle (catch) or declare (throws) them; e.g. IOException.
  2. Unchecked exceptions extend RuntimeException and occur at runtime; the compiler doesn't force handling; e.g. NullPointerException.
  3. Checked usually means a recoverable external condition; unchecked usually means a programming bug.
Worked example
What does the finally block do, and when does it run?
  1. finally contains code that should run regardless of what happened in try/catch.
  2. It runs whether an exception was thrown or not, and even if try or catch executes a return.
  3. It's used for cleanup — closing files, releasing connections — so resources aren't leaked.
⚠ Watch out
  • Catching Exception too broadly hides bugs — catch the specific type you can handle.
  • A return in finally overrides a return in try/catch — avoid it.
  • throw vs throws: throw raises an exception; throws declares that a method may raise one.
Practice this — take a timed mock →
1,300+ questions, scored, with a weak-area report.
Know who's ready. Not who finished.
HomeLibraryPrivacyTerms