❮ Java Keywords
Example
Throw an exception if age is below 18 [print "Access denied"]. If age is 18 or older, print "Access granted":
public class Main {
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...]
}
}
Try it Yourself »
Definition and Usage
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.
Differences between throw
and 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.
❮ Java Keywords
In this guide, we will discuss the difference between throw and throws keywords. Before going though the difference, refer my previous tutorials about throw and throws.
1. Throws clause is used to declare an exception, which means it works similar to the try-catch block. On the other hand throw keyword is used to throw an exception explicitly.
2. If we see syntax wise than throw is followed by an instance of Exception class and throws is followed by exception class names.
For example:
throw new ArithmeticException["Arithmetic Exception"];
and
throws ArithmeticException;
3. Throw keyword is used in the method body to throw an exception, while throws is used in method signature to declare the exceptions that can occur in the statements present in the method.
For example:
Throw:
... void myMethod[] { try { //throwing arithmetic exception using throw throw new ArithmeticException["Something went wrong!!"]; } catch [Exception exp] { System.out.println["Error: "+exp.getMessage[]]; } } ...
Throws:
... //Declaring arithmetic exception using throws void sample[] throws ArithmeticException{ //Statements } ...
4. You can throw one exception at a time but you can handle multiple exceptions by declaring them using throws keyword.
For example:
Throw:
void myMethod[] { //Throwing single exception using throw throw new ArithmeticException["An integer should not be divided by zero!!"]; } ..
Throws:
//Declaring multiple exceptions using throws void myMethod[] throws ArithmeticException, NullPointerException{ //Statements where exception might occur }
These were the main differences between throw and throws in Java. Lets see complete examples of throw and throws keywords.
Throw Example
To understand this example you should know what is throw keyword and how it works, refer this guide: throw keyword in java.
public class Example1{ void checkAge[int age]{ if[age