Throw vs Throws in java
Throws clause in used to declare an exception and thow keyword is used to throw an exception explicitly.
If we see syntax wise than throw is followed by an instance variable and throws is followed by exception class names.
The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).
for e.g.
Throw:
....
static{
try {
throw new Exception("Something went wrong!!");
} catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}
}
....
Throws:
public void sample() throws ArithmeticException{
//Statements
.....
//if (Condition : There is an error)
ArithmeticException exp = new ArithmeticException();
throw exp;
...
}
- By using Throw keyword in java you cannot throw more than one exception but using throws you can declare multiple exceptions. PFB the examples.
for e.g.
Throw:
throw new ArithmeticException("An integer should not be divided by zero!!")
throw new IOException("Connection failed!!")
Throws:
throws IOException, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException