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.