As we know that there are two types of exception – checked and unchecked. While unchecked exception (Runtime) doesn't get checked during compilation. throws keyword is mainly used for handling checked exception as using throws we can declare multiple exceptions in one go.
return type methodname() throws exception_class_name { //method code }
In this example the method "show()" is throwing two checked exceptions so we have declared those 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.*; public class ThrowsDemo { void show(int num)throws IOException, ClassNotFoundException{ if(num==1) throw new IOException("Exception Message1"); else throw new ClassNotFoundException("Exception Message2"); } } class Demo{ public static void main(String args[]){ try{ ThrowsDemo obj=new ThrowsDemo(); obj.show(1); }catch(Exception ex){ System.out.println(ex); } } }
Output
java.io.IOException: Exception Message1
let's look the difference between throw and throws which is one of the popular interview question.
throw | throws | |
---|---|---|
1) | throw keyword is used to explicitly throw an exception. | throws keyword is used to declare an exception. |
2) | Checked exception cannot be propagated. | Checked exception can be propagated. |
3) | throw is followed by an instance. | throws is followed by class. |
4) | throw is used within the method. | throws is used with the method signature. |
5) | You cannot throw multiple exceptions. | You can declare multiple exceptions e.g. public void method()throws IOException, SQLException. |
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc