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.
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