Mastery
Mastery/Java/F. Exceptions
T1 · high-leverage

Checked vs. unchecked exceptions -- the actual compiler-enforced difference

A checked exception (anything extending Exception but not RuntimeException) MUST be either caught or declared in a throws clause -- enforced by the compiler, not a convention. An unchecked exception (RuntimeException and its subclasses) has no such requirement. This is a real compile-time distinction, verified below with an actual compiler error, not just a style guideline.

java
class MyChecked extends Exception {
    MyChecked(String m) { super(m); }
}
class MyUnchecked extends RuntimeException {
    MyUnchecked(String m) { super(m); }
}

void throwsChecked() throws MyChecked {
    throw new MyChecked("checked boom");
}
void throwsUnchecked() {
    throw new MyUnchecked("unchecked boom");
}

try {
    throwsChecked();
} catch (MyChecked e) {
    System.out.println("caught checked: " + e.getMessage());
}

try {
    throwsUnchecked();   // legal to leave uncaught -- the compiler doesn't require handling it
} catch (MyUnchecked e) {
    System.out.println("caught unchecked (not required to): " + e.getMessage());
}

Calling a method that declares a checked exception, without catching it or declaring it yourself, is a real compile error -- reproduced verbatim from a plain javac run:

CheckedFail.java:5: error: unreported exception MyChecked; must be caught or declared to be thrown
        risky();
             ^
1 error

Interview angle

A good debate question as much as a knowledge check: "should this new exception be checked or unchecked?" Strong candidates can articulate the actual tradeoff (checked exceptions force callers to consciously handle a failure mode, but at the cost of API rigidity and the well-known temptation to catch-and-swallow just to satisfy the compiler) rather than reciting the syntax rule alone.

In the industry

Checked exceptions are genuinely controversial in the Java community — much of the modern standard library and popular frameworks (Spring's DataAccessException hierarchy, for instance) deliberately favor unchecked exceptions, partly because checked exceptions compose badly with lambdas and streams (a lambda that calls a checked-exception-throwing method won't even compile without a wrapper). New library APIs in actively maintained codebases skew unchecked by default today, reserving checked exceptions for cases where forcing the caller to handle a specific, recoverable failure is genuinely the right API design.