Difference between Throw and Throws in Java

throws

This article will help you understand the difference between Throw and Throws Keyword in Java :

Throw :

Throw  keyword is used to explicitly throw the exception . It is used to throw both the custom exception and pre-defined exceptions.

throw new ArithmeticException(“/ by zero”);

Scenario : Consider a scenario, where the age needs to be checked and if age is less than 18 then exception should be thrown.

We can achieve this using Throw Keyword.

if(age<18) {

throw new ArithmeticException(“InValid Age”);}

else {

….Normal Flow of the prpgram

}

Throws :

Throws keyword is only used to declare the exceptions and it is not able to actually throw the exception. Throws keyword declares the exceptions which can be occured in the respective method. This keyword is also used for exception propagation

This keyword is used to achieve below two scenarios:

  1. Improves readability: Declaring the exceptions, which are likely to occur, always improves the readability of the program as it indicates the possible exceptions and also ensure that developer handles the possible exceptions.
  2. Propagation of Exception :  To propagate the checked exceptions, throws keyword is used. Exceptions , which should be propagated , needs to be declared using throws keyword in the respective method.

throw vs throws

Thanks for reading this article. I hope , you like it,

For any suggestions / feedback / question / clarification, Kindly post your comments in the below comment box.

Please subscribe our news letter and connect with social media accounts and don’t miss any articles.

Happy Reading!!!

Leave a Reply

Your email address will not be published. Required fields are marked *