How do I throw exceptions in Java?

The exceptions that you catch in a try-catch block must have been raised by a method that you’ve called. You can raise an exception with a statement that consists of the throw keyword, followed by an exception object. This exception object is an instance of any subclass of the Throwable class.

In the example below we have two static methods that throws exception. The first method, throwException() will throw an ArithmethicException when the divider is a zero value integer. The second method, printDate(Date date) will throw a NullPointerException if the date parameter value is null.

package org.kodejava.basic;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ThrowExample {
    public static void main(String[] args) {
        try {
            ThrowExample.throwException();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            ThrowExample.printDate(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void throwException() {
        int x = 6;
        int[] numbers = {3, 2, 1, 0};

        for (int y : numbers) {
            if (y == 0) {
                // Throws an ArithmeticException when about to
                // divide by zero.
                String message = String.format(
                        "x = %d; y = %d; a division by zero.",
                        x, y);
                throw new ArithmeticException(message);
            } else {
                int z = x / y;
                System.out.println("z = " + z);
            }
        }
    }

    public static void printDate(Date date) {
        if (date == null) {
            throw new NullPointerException("Date cannot be null.");
        }
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        System.out.println("Date: " + df.format(date));
    }
}

The output of our code:

z = 2
z = 3
z = 6
java.lang.ArithmeticException: x = 6; y = 0; a division by zero.
    at org.kodejava.basic.ThrowExample.throwException(ThrowExample.java:33)
    at org.kodejava.basic.ThrowExample.main(ThrowExample.java:10)
java.lang.NullPointerException: Date cannot be null.
    at org.kodejava.basic.ThrowExample.printDate(ThrowExample.java:43)
    at org.kodejava.basic.ThrowExample.main(ThrowExample.java:16)

How do I catch multiple exceptions?

If a try block can throw several kind of exceptions, and you want to handle each exception differently, you can put several catch blocks to handle it.

package org.kodejava.basic;

public class MultipleCatchExample {
    public static void main(String[] args) {
        int[] numbers1 = {1, 2, 3, 4, 5};
        int[] numbers2 = {1, 2, 3, 4, 5, 6};

        try {
            // This line throws an ArrayIndexOutOfBoundsException
            MultipleCatchExample.printResult(numbers1);

            // This line throws an ArithmeticException
            MultipleCatchExample.printResult(numbers2);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Finally block is always executed.");
        }
    }

    /**
     * Divide the given first number by the second number.
     *
     * @param x the first number.
     * @param y the second number.
     * @return the result of division.
     */
    private static int divide(int x, int y) {
        return x / y;
    }

    /**
     * Print the output result of divide operation by calling the
     * divide() method.
     *
     * @param numbers integer arrays of the divided number
     * @throws ArrayIndexOutOfBoundsException when an exception
     *                                        occurs.
     */
    private static void printResult(int[] numbers) {
        int x, z, y = 1;
        for (int i = 0; i < 6; i++) {
            x = numbers[i];
            if (i == 5) {
                y = 0;
            }
            z = MultipleCatchExample.divide(x, y);
            System.out.println("z = " + z);
        }
    }
}

How do I use the throws keyword to declare method exceptions?

The throws keyword is used in method declarations to specify which exceptions are not handled within the method body but rather passed to the next higher level of the program. All uncaught exceptions in a method that are not instances of RuntimeException must be declared using the throws keyword.

In the example below you could see that the getConnection() method can cause a ClassNotFoundException when the driver class cannot be found and an SQLException when it fails to initiate a connection to database.

On the other end, the main() method which call the getConnection() method should catch all the exception throws by the getConnection() method in its body.

package org.kodejava.basic;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ThrowsExample {
    public static void main(String[] args) {
        Connection connection = null;

        try {
            // Might throw ClassNotFoundException or SQLException
            // that's why we should catch them.
            connection = getConnection();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Finally is always executed");
            System.out.println("Close connection");
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.out.println("Sql exception caught");
            }
        }
    }

    /**
     * Get database connection.
     *
     * @return Connection
     * @throws ClassNotFoundException when driver class is not found.
     * @throws SQLException           when database error occurs.
     */
    private static Connection getConnection()
            throws ClassNotFoundException, SQLException {

        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://localhost/kodejava",
                "root", "");
    }
}

Without adding the database driver it will get the following exception:

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:375)
    at org.kodejava.basic.ThrowsExample.getConnection(ThrowsExample.java:40)
    at org.kodejava.basic.ThrowsExample.main(ThrowsExample.java:14)
Finally is always executed
Close connection

How do I handle exceptions using try-catch block?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. When an abnormal situation occurs within a method, an Exception object is thrown. This object contains information about the error or unusual problems that occur.

Creating an exception object and handing it to the runtime system is called throwing an exception. If you want to deal with the exceptions where they occur, you can include three kinds of code blocks in a method to handle them. try, catch, and finally blocks.

  • The try block encloses code that may give rise to one or more exceptions.
  • The catch block encloses code that is intended to handle exceptions to a particular type that may be thrown in the associated try block.
  • The code in a finally block is always executed before the method ends, regardless of whether any exceptions are thrown in the try block.
package org.kodejava.basic;

public class ExceptionHandlerExample {

    public static void main(String[] args) {
        int x = 1, y = 0, z = 0;

        try {
            // divide by 0 will throw an exception
            z = ExceptionHandlerExample.divide(x, y);
            System.out.println("z = " + z);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Finally block is always executed.");
        }
    }

    /**
     * Divide the given first number by the second number.
     *
     * @param x the first number.
     * @param y the second number.
     * @return the result of division.
     * @throws RuntimeException when an exception occurs.
     */
    private static int divide(int x, int y) throws RuntimeException {
        return x / y;
    }
}

Here is what happening when we run the program:

java.lang.ArithmeticException: / by zero
    at org.kodejava.basic.ExceptionHandlerExample.divide(ExceptionHandlerExample.java:28)
    at org.kodejava.basic.ExceptionHandlerExample.main(ExceptionHandlerExample.java:10)
Finally block is always executed.

How do I use the shift right “>>” operator?

The signed shift right operator >> shifts a bit pattern to the right. This operator operates with two operand, the left-hand operand to be shifted and the right-hand operand tells how much position to shift.

Shifting a 1000 bit pattern using the >> operator 2 position will produce a 0010 bit pattern. The signed shift right operator produce a result that equals to dividing a number by 2.

package org.kodejava.basic;

public class SignedRightShiftOperator {
    public static void main(String[] args) {
        // The binary representation of 32 is
        // "00000000000000000000000000100000"
        int number = 32;
        System.out.println("number       = " + number);
        System.out.println("binary       = " +
                Integer.toBinaryString(number));

        // Using the shift right operator we shift the bits
        // four times to the right which resulting the result
        // of "00000000000000000000000000000010"
        int shiftedRight = number >> 4;
        System.out.println("shiftedRight = " + shiftedRight);
        System.out.println("binary       = " +
                Integer.toBinaryString(shiftedRight));
    }
}

The result of the code snippet:

number       = 32
binary       = 100000
shiftedRight = 2
binary       = 10