This article will help you understand the difference between Throw and Throws Keyword in Java :
Introduction to Throw and Throws in Java
Throw and Throws keywords are one of the most important keywords in java. Both the keywords are used in the exception handling of Java.
These two keywords are very important for interview purpose so let’s understand these :
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.
Throw vs Throws :
Frequently Asked Questions (FAQ)
Q. Can we use throw and throws together?
A. Yes. throw keyword simply used to throw the exceptions (predefined or custom) and throws keyword propagate the exception so it is possible to use throw and throws together.
Q. What is the difference between throw and throws?
A. You can see the complete list of differences in above section. However , the main different between throw and throws is that throw throws the exception whereas throws only declares the exception.
Q. What is the purpose of the throw and throws keywords?
A. Both keywords are used for exception handling in Java.
Q. Can we use throw without throws Java?
A. Yes, absolutely.
This article explains the throw and throws keyword in Java. It also explains the key difference between these keywords.
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.