How do I use multi-catch statement?

The multi-catch is a language enhancement feature introduces in the Java 7. This allow 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.example.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.example.fundamental;

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);
        }
    }
}
class DivideByZeroException extends Exception {
    DivideByZeroException() {
    }

    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 declares 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.example.fundamental;

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.example.fundamental;

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[] y = {3, 2, 1, 0};

        for (int i = 0; i < y.length; i++) {
            if (y[i] == 0) {
                // Throws an ArithmeticException when about to
                // divide by zero.
                String message = String.format(
                        "x = %d; y = %d; a division by zero.",
                        x, y[i]);
                throw new ArithmeticException(message);
            } else {
                int z = x / y[i];
                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));
    }
}

How do I catch multiple exceptions?

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

package org.kodejava.example.fundamental;

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.example.fundamental;

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 throws ClassNotFoundException or SQLException
            // that's why we should catch them.
            connection = getConnection();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (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
     * @throws SQLException
     */
    private static Connection getConnection()
            throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection(
                "jdbc:mysql://localhost/kodejavadb", "root", "");
    }
}

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 of 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.example.fundamental;

public class ExceptionHandlerExample {

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

        try {
            // divide by 0 will thrown an exception
            z = ExceptionHandlerExample.divide(x, y);
            System.out.println("z = " + z);
        } catch (Exception 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.example.fundamental.ExceptionHandlerExample.divide(ExceptionHandlerExample.java:30)
    at org.kodejava.example.fundamental.ExceptionHandlerExample.main(ExceptionHandlerExample.java:12)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)
Finally block is always executed.

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.example.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.toString());
        }
    }
}

This code snippet print the following output:

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