throws Clause
1. What It Means (beginner)
throws = warning sign on method: "I MIGHT throw this — caller, handle it!" For checked exceptions (files, SQL — compiler forces!). Like "caution: wet floor" board!
2. Code — File Read Warns!
import java.io.*;
class Demo {
static void read() throws IOException { // WARNS (passes duty up!)
BufferedReader br = new BufferedReader(new FileReader("a.txt"));
System.out.println(br.readLine());
br.close();
}
public static void main(String[] args) {
try { read(); } // caller handles!
catch (IOException e) { System.out.println("file missing!"); }
}
}
// throws IOException, SQLException (many, comma-separated!)
3. throws vs throw (exam table — #1 confusion!)
throws (with s!) |
throw (no s!) |
|
|---|---|---|
| Job | warns (declaration!) | throws actually (action!) |
| Where | method signature | inside body |
| Example | void f() throws IOException |
throw new ArithmeticException(); |
4. Rules (traps!)
- Checked exception + no catch + no
throws= COMPILE ERROR! - Unchecked (
Arithmetic,NullPointer) need NOthrows(optional!). - Overriding can't add BIGGER checked (child ≤ parent!).
5. Exam Points
throwsprogram + vsthrowtable — 5-7 marks, very frequent.- Checked-needs-
throws— 3 marks, frequent.