Java Throw Keyword


throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception.

Syntax

throw ThrowableInstance

Example 1

import java.util.*;
class xyz extends Exception
{
 xyz(String message)
 {
     super(message);
 }
}
public class NewMain {


    public static void main(String[] args) {

        int x=5, y=1000;
        try
        {
            float z=((float)x/(float)y);
            if(z < 0.01)
            {
                throw new xyz("Number is too small");
            }
        }
        catch(xyz e)
        {
            System.out.println("Caught My Exception");
            System.out.println(e.getMessage());
        }
    }
}
Output
Caught My Exception
Number is too small

Example 2

public class NewMain{
  
   static void validate(int age)
   {  
     if(age < 18)
     {  
      throw new ArithmeticException("not valid");  
      }
      else  
      {
        System.out.println("welcome to vote");  
       }  
     }
   public static void main(String args[]){  

      validate(14);   
  }  
}  
Output
Exception in thread main java.lang.ArithmeticException:not valid

Share this article on