- In simple terms throws keyword is used in method declaration to show that this type of exception might occour.
- When we talk about throw keyword which is used to throw one exception and it is also used for custom defined exception.
Above diagram clearly explains the throw and throws keyword and now lets discuss the differences between throw and throws.
Throw
- Throw keyword is used inside the function or inside a block of code.
- In throw keyword exceptions must be of type throwable class.
- We can throw only single exception at a time.
Throws
- This keyword is used with method signature and declares an exception , which might be thrown by a method.
- We can declare multiple exceptions with throws keyword.
- Throws keyword declares an exception.
Now let us see the basic example of throw and throws keyword.
package multipleCatch;
public class Multiple{
public static void main(String[] args)throws ArithmeticException {
int a=5,b=0,c;
try {
c=a/b;
}
catch(Exception e) {
System.out.println(“exception is “+e);
}
}
}
package multipleCatch;
public class Multiple{
int a=5,b=0,c;
void checkException() {
c=a/b;
try {
throw new ArithmeticException(“not allowed”);
}
catch(Exception e) {
System.out.println(e);
}
}
public static void main(String[] args){
Multiple multiple=new Multiple();
multiple.checkException();
}
}
Feel free to try this example and comment below.