Exception Handling · Introduction to Java Programming

throw Clause

Watch lectures

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!)

  • throw needs new object: throw new X(...) (not throw X!).
  • After throw, method EXITS (like return!). Code after = unreachable (if always-throw!).
  • throw unchecked anywhere; checked needs throws/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.
  • new need + exit behaviour — 3 marks, frequent.
AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.

← All Introduction to Java Programming modules