Throws Clause in Java - Exception Handling: Throws Keyword Is Used For Handling Checked Exceptions
Throws Clause in Java - Exception Handling: Throws Keyword Is Used For Handling Checked Exceptions
As we know that there are two types of exception checked and unchecked. Checked exception
(compile time) force you to handle them, if you don’t handle them then the program will not
compile.
On the other hand unchecked exception (Runtime) doesn’t get checked during compilation.
Throws keyword is used for handling checked exceptions . By using throws we can declare
multiple exceptions in one go.
What is the need of having throws keyword when you can handle exception using try-catch?
Well, thats a valid question. We already know we can handle exceptions using try-catch block.
The throws does the same thing that try-catch does but there are some cases where you would
prefer throws over try-catch. For example:
Lets say we have a method myMethod() that has statements that can throw either
ArithmeticException or NullPointerException, in this case you can use try-catch as shown below:
try {
catch (ArithmeticException e) {
catch (NullPointerException e) {
But suppose you have several such methods that can cause exceptions, in that case it would be
tedious to write these try-catch for each method. The code will become unnecessary long and
will be less-readable.
One way to overcome this problem is by using throws like this: declare the exceptions in the
method signature using throws and handle the exceptions where you are calling this method by
using try-catch.
Another advantage of using this approach is that you will be forced to handle the exception
when you call this method, all the exceptions that are declared using throws, must be handled
where you are calling this method else you will get compilation error.
try {
myMethod();
catch (ArithmeticException e) {
catch (NullPointerException e) {
In this example the method myMethod() is throwing two checked exceptions so we have
declared these exceptions in the method signature using throws Keyword. If we do not declare
these exceptions then the program will throw a compilation error.
import java.io.*;
class ThrowExample {
if(num==1)
else
try{
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
Output: