throw keyword
By default, when an exception condition occurs the system automatically throw an exception to inform user that there is something wrong. However we can also throw exception explicitly based on our own defined condition. Using “throw keyword” we can throw checked, unchecked and user -defined exceptions.
Let’s have a look at the below example to understand it better.
Example of throw keyword
/* In this program we are checking the Student age * if the student age<12 and weight <40 then our program * should return that the student is not eligible for registration. */ public class ThrowExample { static void checkEligibilty(int stuage, int stuweight){ if(stuage<12 && stuweight<40) { throw new ArithmeticException("Student is not eligible for registration"); } else { System.out.println("Entries Valid!!"); } } public static void main(String args[]){ System.out.println("Welcome to the Registration process!!"); checkEligibilty(10, 39); System.out.println("Have a nice day.."); } }
Output :
Welcome to the Registration process!!Exception in thread "main" java.lang.ArithmeticException: Student is not eligible for registration at beginnersbook.com.ThrowExample.checkEligibilty(ThrowExample.java:9) at beginnersbook.com.ThrowExample.main(ThrowExample.java:18)
As you can see in the above example that we throw an unchecked exception (Runtime exception) based on our own custom defined conditions using “throw keyword”. Similarly we can throw checked and custom exception as well.
Comments
Post a Comment