#Checked and unchecked exceptions
AddedIn JavaScript you can throw anything: an Error, a string, a number, undefined. TypeScript can't say what a function might throw, so catch (e) gives you unknown and you check e instanceof … yourself. Java only lets you throw objects of class Throwable or a subclass, and the class tells you what kind of problem it is. The hierarchy has four parts you need to know:
| Class | Checked? | Examples | What it means |
|---|---|---|---|
Throwable | (root) | anything that can be thrown | |
Error | unchecked | OutOfMemoryError, StackOverflowError | the JVM is in trouble; don't catch it |
Exception (and subclasses that aren't RuntimeException) | checked | IOException, SQLException, InterruptedException | something outside your code failed: a file, a network, a database |
RuntimeException | unchecked | NullPointerException, IllegalArgumentException, IllegalStateException, ArithmeticException | usually a bug, or a rule your caller broke |
Checked means the compiler checks it: a method that can throw a checked exception must either catch it or declare it with throws IOException in its signature, and then every caller faces the same choice. Unchecked exceptions (RuntimeException, Error and their subclasses) need neither. The mental model: a checked exception is part of the method's type, like its return type. String readConfig(String name) throws IOException says "you get a String, or an IOException you must deal with". The closest TypeScript picture is a function returning Result<string, IOError> that the compiler forces you to unwrap, except that Java does it with exceptions.
Checked exceptions were Java's original bet: failures you can't prevent (a missing file, a dropped connection) should be impossible to ignore. Twenty-five years later the industry mostly decided they cost more than they give: they leak implementation details up through every layer (throws SQLException on a controller method), and they don't work with lambdas (see Exception best practices). Modern libraries lean unchecked, and Spring is the clearest example: it translates SQLException into its own DataAccessException hierarchy, which extends RuntimeException, and Jackson 3 (the JSON library in Spring Boot 4) made JacksonException a RuntimeException where Jackson 2's extended IOException. (Both checked with javap on the JARs: Spring 7.1.0, jackson-core 3.1.8 and 2.20.0.)
String readConfig(String name) {
return Files.readString(Path.of(name));
}
void main() {
IO.println(readConfig("config.txt"));
}$ java Report.java
Report.java:2: error: unreported exception IOException; must be caught or declared to be thrown
return Files.readString(Path.of(name));
^
1 error
error: compilation failedString readConfig(String name) throws IOException {
return Files.readString(Path.of(name));
}
int parsePort(String text) {
return Integer.parseInt(text);
}
void main() {
try {
IO.println(readConfig("config.txt"));
} catch (IOException e) {
IO.println("can't read config: " + e);
}
IO.println("port " + parsePort("8080"));
IO.println("port " + parsePort("80a"));
}$ java Report.java
can't read config: java.nio.file.NoSuchFileException: config.txt
port 8080
Exception in thread "main" java.lang.NumberFormatException: For input string: "80a"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:565)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at Report.parsePort(Report.java:6)
at Report.main(Report.java:16)- Left:
Files.readStringis declaredthrows IOException, a checked exception.readConfigneither catches it nor declares it, so the compiler refuses: "unreported exception IOException; must be caught or declared to be thrown". Nothing runs. - Right:
readConfignow declares it (throws IOException), which moves the decision to its caller.maincatches it, so the program compiles. - There's no
config.txtin the folder, soreadStringthrowsjava.nio.file.NoSuchFileException, a subclass ofIOException. Thecatch (IOException e)block matches it and prints the exception'stoString(): its class name and message (the file name). parsePortcallsInteger.parseInt, which can throwNumberFormatException. That's aRuntimeException, soparsePortneeds nothrowsandmainneeds nocatch:"8080"parses fine."80a"doesn't parse. Nothing catches theNumberFormatException, so it escapesmain, the JVM prints the stack trace and exits with status 1. The compiler let this through because it's unchecked: the compiler only forces you to think about checked exceptions.
void main() {
try {
IO.println("hello");
} catch (IOException e) {
IO.println("never");
}
}Show answer
void main() {
try {
IO.println("hello");
} catch (IOException e) {
IO.println("never");
}
}$ java Never.java
Never.java:4: error: exception IOException is never thrown in body of corresponding try statement
} catch (IOException e) {
^
1 error
error: compilation failed- No: the compiler knows
IO.printlncan't throw a checkedIOException, so acatchfor it is dead code, and for checked exceptions that's an error: "exception IOException is never thrown in body of corresponding try statement". - The same check is what makes
throwsdeclarations trustworthy: the compiler tracks exactly which checked exceptions each statement can throw. catch (Exception e)orcatch (RuntimeException e)would compile, because those can also catch unchecked exceptions, which any code may throw.