Packages & Exception Handling · Lesson 68 of 150
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.
01What 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.
02Why 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.
03Real-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.
04Syntax
javathrow new ExceptionType("error message");
05Example Program
javapublic 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