What is the throw exception?

In Java, we can explicitly throw an exception using the keyword throw. The throw keyword is used to create either checked or unchecked exception. This action raises an exception and requires the calling method to catch the exception or pass the exception to the next level.

Syntax

Syntax to throw an exception is very simple and straight-forward.

throw new exception_class("error message");

Example 1

In the following example program, we are raising an arithmetic exception if the number equals to zero.

public class ThrowExample1 {

    public static void main(String[] args) {

        int numA = 100;
        int numB = 0;

        try {

            // Check input is valid or not?
            if (numB == 0) {

                // Throw an exception
                throw new ArithmeticException("You should not divide a number by zero!");
            }

            // Divide numA by numB.
            System.out.println(numA / numB);

        } catch (Exception e) {
            System.out.println(e);
        }

    }
}

Example 2

In the following example program, we are raising an exception if the user is not eligible to vote.

public class ThrowExample2 {

    public static void main(String[] args) {

        int age = 17;

        try {

            // Check if user is eligible or not
            if (age < 18) {

                // Throw an exception
                throw new Exception("Oops you are not eligible to vote!");
            }

            // User is eligible
            System.out.println("You are eligible to vote.");

        } catch (Exception e) {

            // Handle the exception
            System.out.println(e);
        }

    }
}