The throws keyword indicates what exception type may be thrown by a method.
There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.
public class MyClass {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
The throw Statement All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object.
Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.
throw someThrowableObject;
Let's look at the throw statement in context.
public class MyClass {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}