The throw keyword is used to send an error or exception when something goes wrong in your program. It helps you stop the normal flow and handle problems clearly.
0
0
Throw keyword in Java
Introduction
When you want to stop the program because a wrong value is found.
When you want to tell the program to handle a special error case.
When you want to create your own error message for a problem.
When you want to pass an exception to another part of the program to handle.
When you want to make sure the program does not continue with bad data.
Syntax
Java
throw new ExceptionType("Error message");
You must create a new exception object with new before throwing it.
The throw keyword only sends one exception at a time.
Examples
This throws an exception when an invalid age is found.
Java
throw new IllegalArgumentException("Invalid age");
This throws an exception if an object is unexpectedly null.
Java
throw new NullPointerException("Object is null");
This throws a general runtime exception with a message.
Java
throw new RuntimeException("Something went wrong");
Sample Program
This program checks if a number is positive. If the number is negative, it throws an exception with a message. Otherwise, it prints the number.
Java
public class ThrowExample { public static void checkNumber(int number) { if (number < 0) { throw new IllegalArgumentException("Number must be positive"); } else { System.out.println("Number is " + number); } } public static void main(String[] args) { checkNumber(10); checkNumber(-5); } }
OutputSuccess
Important Notes
When you use throw, the program stops running the current method unless the exception is caught.
You can only throw objects that are subclasses of Throwable, like Exception or Error.
Use throw to create clear and meaningful error messages for easier debugging.
Summary
throw sends an exception to stop normal program flow when an error happens.
You create a new exception object and use throw to send it.
It helps make your program safer by handling problems clearly.