Use of Throw keyword

Throw

  • Throw is used to generate custom exception.
  •  You can write throw keyword inside method.
  •  Throw is object type it means after throw you have create object of Exception class.
Program to generate custom exception using throw

package exceptionHandling;

import java.util.Scanner;

//Class that extends Throwable
class Myexception extends Throwable
 {
	//Empty body
 }

//main class
public class Throw 
{
public static void main(String[] args) 
  {
	
	Scanner c=new Scanner(System.in);
	System.out.println("enter your age");
	
	int n=c.nextInt();
	
	System.out.println("checking......");
	
	if(n<18)
	{
		
		try 
		{	
		  throw new myexception();
		}
		
		catch (myexception e) 
		{
		 System.out.println("try next year,your age is not valid");
		}
		 
	  }
	
	   else
	     {
	        System.out.println("thank you for voting ");
	     }	
	
       }
	
}
output:

enter your age
17
checking......
try next year,your age is not valid

Leave a Reply