Throws clause in java – Exception handling
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:
public void myMethod()
{
try {
// Statements that might throw an exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}
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.
public void myMethod() throws ArithmeticException, NullPointerException
{
// Statements that might throw an exception
}
public static void main(String args[]) {
try {
myMethod();
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}
Example of throws Keyword
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 {
void myMethod(int num)throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException");
}
}
public class Example1{
public static void main(String args[]){
try{
ThrowExample obj=new ThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Output:
java.io.IOException: IOException Occurred
Leave Comment