throw keyword in java

The throw keyword in java is used to throw an exception from a method or block of code. If you want to throw an exception on the basis of certain conditions, you can use throw keyword. For example, if a user entered the NULL/BLANK password we should throw an exception to the client. We can throw either checked or unchecked exceptions. 

throw keyword in java

During the execution of the method if the compiler encounters a throw keyword then execution of the current method is stopped and returned to the caller. The compiler finds the nearest try block if it has a catch block that matches with throwing an exception then its handle by catch block otherwise try to find next try block and so on. If no matching catch is found, then the default exception handler will be executed automatically.

method()
{ 
   throw InstanceOfException;
}
public class ExampleOfThrowException
{  
   static void validationOnNumbers(int number)
   {  
     if(number <= 0)  
      throw new ArithmeticException("This number is not allowed");  
     else  
      System.out.println("Hello!!!!!");  
   }  
   public static void main(String args[]){  
	   validationOnNumbers(0);  
      System.out.println("rest of the code...");  
  }  
}

Output:  Exception in thread “main” java.lang.ArithmeticException: This number is not allowed at ExampleOfThrowException.validationOnNumbers(ExampleOfThrowException.java:4) at ExampleOfThrowException.main(ExampleOfThrowException.java:9)

The important thing about throw keyword:

  1. The instance must be of type Throwable or a subclass of Throwable.
  2. You can throw user(custom) exceptions because they extend Exception class and Exception extending the Throwable.
  3.  You can throw one exception at a time.

The need to java throw exception by throw keyword: If you want to apply some set of rules in a program, then throw an exception explicitly using the throw keyword. For example, you can throw ArithmeticException if the user enters a number less than 0, or any other numbers.

3 thoughts on “throw keyword in java”

Leave a Comment