How do I use multi-catch statement?

The multi-catch is a language enhancement feature introduces in the Java 7. This allows us to use a single catch block to handle multiple exceptions. Each exception is separated by the pipe symbol (|).

Using the multi-catch simplify our exception handling and also reduce code duplicates in the catch block. Let’s see an example below:

package org.kodejava.lang;

import java.io.IOException;
import java.sql.SQLException;

public class MultiCatchDemo {
    public static void main(String[] args) {
        MultiCatchDemo demo = new MultiCatchDemo();
        try {
            demo.callA();
            demo.callB();
            demo.callC();
        } catch (IOException | SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void callA() throws IOException {
        throw new IOException("IOException");
    }

    private void callB() throws SQLException {
        throw new SQLException("SQLException");
    }

    private void callC() throws ClassNotFoundException {
        throw new ClassNotFoundException("ClassNotFoundException");
    }
}

How do I create custom exception class?

You can define your own exception class for your application specific purposes. The exception class is created by extending the java.lang.Exception class for checked exception or java.lang.RuntimeException for unchecked exception. By creating your own Exception classes, you could identify the problem more precisely.

package org.kodejava.basic;

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

        try {
            int z = CustomExceptionExample.divide(x, y);
            System.out.println("z = " + z);
        } catch (DivideByZeroException e) {
            e.printStackTrace();
        }
    }

    public static int divide(int x, int y) throws DivideByZeroException {
        try {
            return (x / y);
        } catch (ArithmeticException e) {
            String m = x + " / " + y + ", trying to divide by zero";
            throw new DivideByZeroException(m, e);
        }
    }
}
package org.kodejava.basic;

class DivideByZeroException extends Exception {
    DivideByZeroException() {
        super();
    }

    DivideByZeroException(String message) {
        super(message);
    }

    DivideByZeroException(String message, Throwable cause) {
        super(message, cause);
    }
}

How do I use checked and unchecked exception?

By throwing a checked exception, you force the caller to handle the exception in a catch block. If a method throws a checked exception, it must declare that it throw the exception in the method declaration.

All exceptions are checked exceptions, except for those indicated by java.lang.Error, java.lang.RuntimeException, and their subclasses.

Runtime exception are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. Runtime exceptions are those indicated by java.lang.RuntimeException and its subclasses.

RuntimeException are known as unchecked exception. It doesn’t require to declare the unchecked exception in the method declaration.

package org.kodejava.basic;

import java.io.File;
import java.io.IOException;

public class ExceptionExample {
    public static void main(String[] args) {
        // You must catch the checked exception otherwise you get a
        // compile time error.
        try {
            ExceptionExample.checkFileSize("data.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // The unchecked exception doesn't requires you to catch
        // it and it doesn't produce a compile time error.
        ExceptionExample.divide();
    }

    /**
     * This method throws a Checked Exception, so it must declare the
     * Exception in its method declaration
     *
     * @param fileName given file name
     * @throws IOException when the file size is to large.
     */

    public static void checkFileSize(String fileName) throws IOException {
        File file = new File(fileName);
        if (file.length() > Integer.MAX_VALUE) {
            throw new IOException("File is too large.");
        }
    }

    /**
     * This method throws a RuntimeException.
     * There is no need to declare the Exception in method declaration
     *
     * @return a division result.
     * @throws ArithmeticException when arithmetic exception occurs.
     */
    public static int divide() throws ArithmeticException {
        int x = 1, y = 0;
        return x / y;
    }
}

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 log an exception?

In this example you can see how we can log an exception when it occurs. In the code below we are trying to parse an invalid date which will give us a ParseException. To log the exception we call the Logger.log() method, passes the logger Level, add some user-friendly message and the Throwable object.

package org.kodejava.util.logging;

import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class LoggingException {
    private static Logger logger =
            Logger.getLogger(LoggingException.class.getName());

    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        df.setLenient(false);

        try {
            // Try to parse a wrong date.
            Date date = df.parse("12/30/1990");

            System.out.println("Date = " + date);
        } catch (ParseException e) {
            // Create a Level.SEVERE logging message
            if (logger.isLoggable(Level.SEVERE)) {
                logger.log(Level.SEVERE, "Error parsing date", e);
            }
        }
    }
}

The code above will produce the following log message.

Oct 07, 2021 8:21:44 PM org.kodejava.util.logging.LoggingException main
SEVERE: Error parsing date
java.text.ParseException: Unparseable date: "12/30/1990"
    at java.base/java.text.DateFormat.parse(DateFormat.java:399)
    at org.kodejava.util.logging.LoggingException.main(LoggingException.java:20)

How do I get an exception stack trace message?

In this example we use the java.io.StringWriter and java.io.PrintWriter class to convert stack trace exception message to a string.

package org.kodejava.io;

import java.io.StringWriter;
import java.io.PrintWriter;

public class StackTraceToString {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (Exception e) {
            // Create a StringWriter and a PrintWriter both of these object
            // will be used to convert the data in the stack trace to a string.
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);

            // Instead of writing the stack trace in the console we write it
            // to the PrintWriter, to get the stack trace message we then call
            // the toString() method of StringWriter.
            e.printStackTrace(printWriter);

            System.out.println("Error = " + stringWriter);
        }
    }
}

This code snippet print the following output:

Error = java.lang.ArithmeticException: / by zero
    at org.kodejava.io.StackTraceToString.main(StackTraceToString.java:9)