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
javathrow new ExceptionType("error message");
5. Example 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 above6. Key Points to Remember
throwis used with a single exception object, created usingnew.- After a
throwstatement executes, the rest of that method stops running immediately. throwis typically combined with anifcheck to catch invalid conditions in your own logic.