11.6 Throwing an Exception

So far, you have only been catching exceptions that are thrown by the Java run-time system. However, you can throw an exception manually using the throw statement. The general format of the throw statement is as follows:

throw new ExceptionType(Messsge);

The Message argument contains a custom error message that can be retrieved from the exception objects method. If you do not pass a message to the constructor, the exception will have a null message. Here is an example of a throw statement:

throw new InputMismatchException("Positive number required");

The following program contains the method getSide, which reads a int and
returns it to the method main. If the number entered by the user contains a negative number, the method getSide throws an InputMismatchException.

Rather than catch and handle this exception, the method getSide throws this exception. The catch block of the method main catches the InputMismatchException.

import java.util.Scanner;
import java.util.InputMismatchException;

public class Exercise 
{
    public static void main(String[] args) 
    {
        try 
        {
            int squareSide = getSide();
            show(squareSide);
        }
        catch (InputMismatchException ex) 
        {
            ex.printStacktrace();
        }
    }

    private static int getSide() 
    {
        int side;
        Scanner console = new Scanner(System.in);

        System.out.print("Enter Side of Square: ");
        side = console.nextInt();

        if (side < 0) 
        {
            throw new InputMismatchException("Positive number required");
        }

        return side;
    }

    private static void show(int side) 
    {
        System.out.println("Side: " + side);
        System.out.println("Area: " + (side * side));
    }
}

Sample Run # 1

Enter Side of Square: 10

Side: 10
Area: 100

Sample Run # 2

Enter Side of Square: -9
java.util.InputMismatchException: Positive number required
at Exercise.getSide(Exercise.java:29)
at Exercise.main(Exercise.java:10)

In Sample Run 1, the method getNumber successfully reads the number and returns it to the method main.

In Sample Run 2, the user enters a negative number. The statement in method getSide throws an InputMismatchException, which is thrown and control goes back to the method main, which throws an InputMismatchException thrown by the method getSide. The catch block in catches this exception, and outputs the appropriate message.

In above example we have used printStackTrace method to determine the order in which the methods were called and where the exception was handled.

 

Note that the declaration of the getSide method does not contain a throws clause. InputMismatchException is not a checked exception, so getSide is not required to state that it might occur.