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);
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply