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?
- Checked exceptions are verified at compile time — the compiler forces you to handle (catch) or declare (throws) them; e.g. IOException.
- Unchecked exceptions extend RuntimeException and occur at runtime; the compiler doesn't force handling; e.g. NullPointerException.
- Checked usually means a recoverable external condition; unchecked usually means a programming bug.
Answer: Checked are compile-time-enforced (must catch/declare); unchecked (RuntimeException) are runtime and not enforced.
Worked example
What does the finally block do, and when does it run?
- finally contains code that should run regardless of what happened in try/catch.
- It runs whether an exception was thrown or not, and even if try or catch executes a return.
- It's used for cleanup — closing files, releasing connections — so resources aren't leaked.
Answer: finally always runs after try/catch (even on return) and is used for cleanup like closing resources.
⚠ 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.