throw Clause
1. What It Does (beginner)
throw = YOU cause the exception (handover the problem object!). Validate + reject bad input: negative age? throw new IllegalArgumentException("age < 0!"). Like referee whistle!
2. Code — Guard Method (exam pattern!)
static void setAge(int age) {
if (age < 0) throw new IllegalArgumentException("age can't be negative!"); // THROW!
System.out.println("age=" + age);
}
public static void main(String[] args) {
try { setAge(-5); }
catch (IllegalArgumentException e) { System.out.println("caught: " + e.getMessage()); }
setAge(20); // age=20
}
Custom exception (own type!):
class LowBalance extends Exception { // checked (extends Exception!)
LowBalance(String m) { super(m); }
}
// ... throw new LowBalance("min 500!"); (needs throws/catch!)
3. throw Rules (traps!)
throwneedsnewobject:throw new X(...)(notthrow X!).- After
throw, method EXITS (like return!). Code after = unreachable (if always-throw!). throwunchecked anywhere; checked needsthrows/catch!
4. throw vs throws (memory hook!)
throw = action (verb, inside!). throws = warning (signature, with s!). One letter s = big difference (exam's favourite!).
5. Exam Points
- Guard + custom exception program — 5-7 marks, very frequent.
newneed + exit behaviour — 3 marks, frequent.