Skip to content
C

throw

throw is used to manually create and trigger an exception yourself, rather than waiting for Java to generate one automatically due to some code error.


1. What is throw?

throw is used to manually create and trigger an exception yourself, rather than waiting for Java to generate one automatically due to some code error.

2. Why is it used?

Sometimes your own program logic detects an invalid situation that Java itself wouldn't naturally flag — like a negative age value. throw lets you signal this problem explicitly as an exception.

3. Real-Life Example

Think of a security guard manually raising an alarm after personally noticing something suspicious, even though no automatic sensor detected anything. throw lets your code raise this kind of manual alert.

4. Syntax

java
throw new ExceptionType("error message");

5. Example Program

java
public class ThrowDemo { static void checkAge(int age) { if (age < 18) { throw new IllegalArgumentException("Age must be 18 or above"); } System.out.println("Age is valid."); } public static void main(String[] args) { checkAge(15); } }

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Age must be 18 or above

6. Key Points to Remember

  • throw is used with a single exception object, created using new.
  • After a throw statement executes, the rest of that method stops running immediately.
  • throw is typically combined with an if check to catch invalid conditions in your own logic.