Throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself. It is used to declare an exception, it tells the programmer that an exception may occur hence warning the programmer to also write exception handling mechanism to catch the exception.
It is usually used to throw checked exceptions and not unchecked ones. As unchecked exceptions can be controlled and exception handling mechanism can be used to catch it, so now the checked exceptions can be propagated/forwarded to another calling method.
You can throw multiple exceptions from a single method by seperating them using comma.
Example : Check exception propagation using throws keyword
import java.io.IOException;
public class ThrowsException {
static void testMethod(int num) throws IOException, ClassNotFoundException {
if (num == 1)
throw new IOException("** IOException Occurred here **");
else
throw new ClassNotFoundException("** ClassNotFoundException **");
}
public static void main(String[] args) {
try {
testMethod(1);
} catch (Exception ex) {
System.out.println(ex);
}
}
}
OUTPUT
** IOException Occurred here **
Important : Why do we need throws ?
Why do we need throws when we can handle exceptions using try catch block ?
This is a valid question right ?
We need it for 2 important reasons :
- In a scenarios where you have to handle multiple exceptions in various methods, it becomes very tedious to write try catch block in all the methods, so here comes throws into picture, we use throws in the method definition of various methods but catch them in one of the calling method.
- Another advantage is that you will be forced to handle all the exceptions which is a good practice otherwise you will get compilation errors.
Summary
So here we are, we hope now you are confident and know how to use throws keyword in Exceptions in java.
We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.