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.
The general form of throws keyword is:
Let's see a program for better understanding :
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.
java.io.IOException: Exception Message1
let's look the difference between throw and throws which is one of the popular interview question.
|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.