Checked — compiler enforces handling. Unchecked — runtime only, compiler doesn't force handling.
Analogy: Checked are like required safety inspections — the compiler won't let your code ship until you prove you've handled them. Unchecked are like unexpected accidents — you should prepare, but the compiler doesn't require proof.
Checked exceptions:
Exception (but NOT RuntimeException).throws declaration.IOException, SQLException, FileNotFoundException.1// Must handle or declare:2public void readFile(String path) throws IOException {3 FileInputStream fis = new FileInputStream(path);4}56// Catching:7public void loadConfig() {8 try {9 FileInputStream fis = new FileInputStream("config.txt");10 } catch (FileNotFoundException e) {11 System.err.println("Config not found: " + e.getMessage());12 } catch (IOException e) {13 System.err.println("Error: " + e.getMessage());14 }15}
Unchecked exceptions:
RuntimeException.NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.1// These compile without try/catch:2String str = null;3// str.length(); // NullPointerException45int[] arr = new int[5];6// arr[10] = 1; // ArrayIndexOutOfBoundsException78int result = 10 / 0; // ArithmeticException910// Custom unchecked:11public void setAge(int age) {12 if (age < 0) throw new IllegalArgumentException("Invalid age: " + age);13 this.age = age;14}
Exception hierarchy:
Throwable
├── Exception
│ ├── RuntimeException (unchecked)
│ ├── IOException (checked)
│ └── SQLException (checked)
└── Error (don't catch these)
├── OutOfMemoryError
└── StackOverflowError
Key differences:
Exception. Unchecked — extends RuntimeException.Best practices:
Error (JVM-level problems).