Java › Exceptions
What is the difference between checked and unchecked exceptions in Java, and how does the compiler treat each differently?
BeginnerAnswer
Checked exceptions (subclasses of Exception but not RuntimeException, like IOException) must either be caught or explicitly declared in a method's throws clause, enforced by the compiler at compile time -- representing conditions a well-behaved caller should anticipate and handle; unchecked exceptions (subclasses of RuntimeException, like NullPointerException or IllegalArgumentException) require no such compile-time declaration or handling, typically representing programming errors or conditions the caller usually can't reasonably recover from, letting them propagate freely up the call stack without cluttering every intermediate method's signature.
// Checked exception -- must be caught or declared
public void readFile(String path) throws IOException {
Files.readString(Path.of(path)); // IOException is checked, compiler enforces handling
}
// Unchecked exception -- no compiler enforcement
public int divide(int a, int b) {
return a / b; // ArithmeticException is unchecked, no throws declaration required
}Real-world example A file-processing method's throws IOException declaration forces every calling method up the chain to either handle the exception or explicitly propagate it further, ensuring file I/O failures can never be silently ignored by accident, unlike an unchecked NullPointerException which requires no such compile-time acknowledgment.