Java

How To Throw Exception In Java ?

ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, and more exception types have previously been created in Java. These exceptions are programmed to occur in different-2 circumstances. For instance, the ArithmeticException is triggered when an integer is divided by zero. The ArrayIndexOutOfBoundsException is triggered when an array element is accessed outside of its constraints.

Using the throw keyword, we may explicitly throw an exception and establish our own set of circumstances or rules. When dividing a number by 5, for instance, or any other number, we may throw an exception. All we need to do is establish the condition and use the throw keyword to create the exception. The throw keyword may also be used to throw custom exceptions; for more information, see Java’s Custom Exceptions.

Syntax of throw keyword:

throw new exception_class("error message");

For example:

throw new ArithmeticException("dividing a number by 5 is not allowed in this program");

Example of throw keyword

Consider a requirement that states that students may only be registered if they are under the age of 12 and under 40 pounds. If any of these conditions is not satisfied, the user should get an ArithmeticException with the message “Student is not eligible for registration.” By including the code in the procedure that verifies a student’s eligibility, we have put the reasoning into practice. If the entered student’s age and weight don’t fit the bill, the toss keyword is used to raise an exception.

/* 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("Student Entry is 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)

Related Articles

Leave a Reply

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

Back to top button