Careeroza
Checked vs Unchecked
Comparison
| Checked | Unchecked | |
|---|---|---|
| Extends | Exception (not RuntimeException) | RuntimeException |
| Compiler forces handling | yes: catch it or declare throws | no |
| Represents | expected problems outside your control (file missing, network down) | programming bugs (null, bad index, bad argument) |
| Examples | IOException, SQLException, InterruptedException | NullPointerException, IllegalArgumentException |
The Compiler Checks Checked Exceptions
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
String text = Files.readString(Path.of("data.txt"));
// error: unreported exception IOException; must be caught or declared to be thrown
}
}Example
Two ways to fix it: catch it, or declare it with throws and let the caller decide.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
static String readConfig(String name) throws IOException { // option 2: declare
return Files.readString(Path.of(name));
}
public static void main(String[] args) {
try { // option 1: catch
System.out.println(readConfig("missing-config.txt"));
} catch (IOException e) {
System.out.println("Could not read config: " + e.getClass().getSimpleName());
}
}
}Output
Could not read config: NoSuchFileException