This article will help you understand the difference between Throw and Throws Keyword in Java :
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.
throw new ArithmeticException(“InValid Age”);}
….Normal Flow of the prpgram
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:
- 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.
- 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.
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.