In Java, the throw
keyword is used to explicitly throw an exception from a method or a block of code. It signals an error condition that must be handled or propagated up the call stack. This is different from throws
, which is used in method declarations to indicate that a method can throw specific exceptions.
throw
KeywordWhen you use throw
, you are manually creating and throwing an exception object of a specific type. It allows you to handle specific conditions in your code where you want to signal an error. The throw
statement is typically followed by an instance of a class that extends Throwable
, such as Exception
or RuntimeException
.
Syntax:
throw new ExceptionType("Error message");
Here’s a simple example of throwing an exception when a condition is not met:
public class Example {
public static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
} else {
System.out.println("Age is valid.");
}
}
public static void main(String[] args) {
try {
checkAge(16); // This will throw an exception
} catch (IllegalArgumentException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Explanation:
checkAge
method, if the age is less than 18, an IllegalArgumentException
is thrown with a message.main
method calls checkAge(16)
, which triggers the exception.catch
block catches this exception and prints the error message.