Custom Exception in Java

In this tutorial, we will learn how to create custom exceptions in Java. I would recommend reading Exception handling in Java before reading this tutorial.

1. What is Custom Exception in Java?

Java provides many different Exception classes to handle all kind of Exceptions and code failures. However, sometimes we may need our own custom exception handling code and messages.

It is just a normal class which inherits the java.lang.Exception class or its child classes.

Let’s see how to create a custom exception in Java.

2. How to Create Custom Exception in Java?

Let’s suppose we need a class that checks Invalid numbers so we will define a class and extends java.lang.Exception class. In this way, you can define your own custom exception class and set your own custom messages and logic.

public class InvalidNumberChecker extends ArithmeticException {

	InvalidNumberChecker(String errorMessage) {
		super(errorMessage);
	}
}

Main Class:

public class Example {

	public static void main(String[] args) {

		int a = 10;
		int b = 5;

		if (b > a) {
			System.out.println("Greater Number");
		} else {
			throw new InvalidNumberChecker("Message from Custom Exception class");
		}
	}
}

Output:

Exception in thread "main" packageName.InvalidNumberChecker: Message from Custom Exception class