Intermediate⏱️ 11 min📘 Topic 15 of 22

⚠️ Java Exception Handling — try/catch, Checked vs Unchecked

Master Java exception handling — try/catch/finally, checked vs unchecked exceptions, try-with-resources, custom exceptions, throw vs throws and the exception hierarchy. With examples.

Exceptions signal that something went wrong. Java's checked/unchecked split is a top interview topic.

🌳 The hierarchy

ThrowableError (JVM problems — don't catch) and Exception. ExceptionRuntimeException (unchecked) and everything else (checked).

✅ Checked vs unchecked

  • Checked (IOException, SQLException) — the compiler forces you to handle or declare them with throws. For recoverable, expected failures.
  • Unchecked (NullPointerException, IllegalArgumentException) — extend RuntimeException, not enforced. For programming bugs.

🛡️ try / catch / finally

try {
  risky();
} catch (IOException e) {
  log(e.getMessage());
} finally {
  cleanup();   // always runs
}

🔐 try-with-resources (Java 7+)

Auto-closes anything implementing AutoCloseable — no finally needed:

try (var reader = new BufferedReader(new FileReader("f.txt"))) {
  return reader.readLine();
}  // reader.close() called automatically

🚨 throw vs throws

  • throw — raise an exception now: throw new IllegalArgumentException("bad");
  • throws — declare a method may throw: void f() throws IOException

🏷️ Custom exceptions

Extend RuntimeException (unchecked) or Exception (checked) to model domain errors. Keep messages actionable.

💻 Code Examples

try-with-resources auto-closes

try (Scanner sc = new Scanner(System.in)) {
  int n = sc.nextInt();
  System.out.println(n * 2);
}  // Scanner closed automatically
Output:
Reads an int and prints its double; resource closed on exit.

finally always runs

static int demo() {
  try { return 1; }
  finally { System.out.println("cleanup"); }
}
System.out.println(demo());
Output:
cleanup
1

Custom unchecked exception

class InsufficientFundsException extends RuntimeException {
  InsufficientFundsException(String msg) { super(msg); }
}
throw new InsufficientFundsException("balance too low");
Output:
Throws a domain-specific, unchecked exception.

⚠️ Common Mistakes

  • Catching Exception (or Throwable) broadly and swallowing it — hides real bugs; catch specific types.
  • Returning from finally — it overrides any return/throw from try, masking exceptions.
  • Catching and ignoring — at minimum log it; never leave an empty catch block.
  • Using exceptions for normal control flow — they're slow on the throw path and obscure intent.

🎯 Interview Questions

Real questions asked at top product and service-based companies.

Q1.What's the difference between checked and unchecked exceptions?Beginner
Checked exceptions (e.g., IOException) extend Exception and must be caught or declared with throws — for recoverable conditions. Unchecked exceptions extend RuntimeException, aren't compiler-enforced, and usually indicate programming bugs (e.g., NullPointerException).
Q2.What's the difference between throw and throws?Beginner
throw actually raises an exception instance (throw new X()). throws is a method declaration listing the checked exceptions the method may propagate to its caller.
Q3.What is try-with-resources?Intermediate
A try statement (Java 7+) that declares resources implementing AutoCloseable; the JVM closes them automatically in reverse order when the block exits, even on exception — eliminating manual finally cleanup.
Q4.Does finally always execute?Intermediate
Almost always — even if try/catch returns or throws. The only exceptions are System.exit(), JVM crash, or an infinite loop/daemon-thread kill. Avoid returning from finally, as it masks exceptions and returns.
Q5.What's the difference between Error and Exception?Advanced
Both extend Throwable. Error represents serious JVM problems (OutOfMemoryError, StackOverflowError) you generally shouldn't catch. Exception represents conditions an application can reasonably handle.

🧠 Quick Summary

  • Throwable → Error (don't catch) and Exception.
  • Checked = compiler-enforced (handle or declare); unchecked = RuntimeException.
  • finally always runs; try-with-resources auto-closes AutoCloseable.
  • throw raises; throws declares.
  • Catch specific types; never swallow exceptions silently.