throw keyword in JAVA

Throw in JAVA

  • In JAVA the throw keyword is used to throw custom or user defined exceptions.
  • We can throw checked as well as unchecked exceptions using throw keyword.

Let us take an example, where we need to validate if the month number entered is proper or not.

Program(Save as Throw.java)

import java.util.*;
public class Throw
{
    public static void main(String args[]) 
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter month number");
        int month = sc.nextInt();
        try
        {
            if(month<1 || month>12){
                 throw new ArithmeticException();
            }
            else
                System.out.println("You've entered a valid month number");
        }
        catch(ArithmeticException e)
        {
            System.out.println(month+ " is an Invalid Month Number!!!");
         }
    }  
}

Output

$javac Throws.java
$java Throws
Enter month number
13
13 is an Invalid Month Number!!!

We have used an already existing unchecked excpetion(Arithmetic Exception) as used it according to our needs, what if want to create our own exception class, let's see how we can achieve this.

Program

import java.util.*;
public class Throws
{
    public static void main(String args[]) 
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter month number");
        int month = sc.nextInt();
        try
        {
            if(month<1 || month>12){
                throw new MyException(month+ " is an Invalid Month Number!!!");
            }
            else
                System.out.println("You've entered a valid month number");
        }
        catch(MyException e)
        {
            System.out.println("Plz try AGAIN!!!");
        }
    } 
}

class MyException extends Exception
{
    MyException(String str){
        System.out.println(str);
    }
}

Output

$javac Throws.java
$java Throws
Enter month number
13
13 is an Invalid Month Number!!!
Plz try AGAIN!!!

In the above program, we have created our own exception class which is extending the super class(Exception).

Share Me!
  •  
  •  
  •  
  •  
  •  
  •