We have heard about the throw and throws keyword in Exception handling, which tends to be an important part of handling an exception.
- In simple terms, the throws keyword is used in a method declaration to show that this type of exception might occur.
- When we talk about the throw keyword which is used to throw one exception and is also used for a custom-defined exception.
The above diagram clearly explains the throw and throws keyword and now let’s discuss the differences between throw and throws.
Throw
- The 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 a 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 the throws keyword.
- Throws keyword declares an exception.
Now let us see the basic example of the throw and throws keyword.
//throws keyword example
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);
}
}
}
//throw keyword example
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.