Java throw Keyword
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted":
public class MyClass {
static void checkAge(int age) {
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...)
}
}
Run example »
Definition and Usage
The throw
keyword is used to create a custom error.
The throw
statement is used together with an exception type. There are many exception types available in Java: ArithmeticException
, ClassNotFoundException
, ArrayIndexOutOfBoundsException
, SecurityException
, etc.
The exception type is often used together with a custom method, like in the example above.
Differences between throw
and throws
:
throw | throws |
---|---|
Used to throw an exception for a method | Used to indicate what exception type may be thrown by a method |
Cannot throw multiple exceptions | Can declare multiple exceptions |
Syntax:
|
Syntax:
|
Related Pages
Read more about exceptions in our Java Try..Catch Tutorial.