Checked — compile-time enforced. Unchecked — runtime only.
Analogy: Checked = required safety inspections. Unchecked = unexpected accidents.
Checked:
Exception (not RuntimeException).throws.IOException, SQLException.1public void readFile(String path) throws IOException {2 FileInputStream fis = new FileInputStream(path);3}45public void loadConfig() {6 try {7 FileInputStream fis = new FileInputStream("config.txt");8 } catch (FileNotFoundException e) {9 System.err.println("Not found");10 } catch (IOException e) {11 System.err.println("Error");12 }13}
Unchecked:
RuntimeException.NullPointerException, ArithmeticException.1String str = null;2// str.length(); // NullPointerException34int[] arr = new int[5];5// arr[10] = 1; // ArrayIndexOutOfBoundsException67int result = 10 / 0; // ArithmeticException89// Custom unchecked:10public void setAge(int age) {11 if (age < 0) throw new IllegalArgumentException("Invalid");12 this.age = age;13}
Hierarchy:
Throwable
├── Exception
│ ├── RuntimeException (unchecked)
│ ├── IOException (checked)
│ └── SQLException (checked)
└── Error (don't catch)
Differences:
Exception. Unchecked — RuntimeException.Best practices:
Error.