Java Program to Create Custom Exception Class

In this Java program, we will learn to create a user defined exception class. In Java, you can create your own custom exception by defining a new class that extends the Exception class or one of its subclasses.

Creating custom exceptions allows you to provide more meaningful error messages and to handle specific error conditions in your code. It's important to note that custom exceptions should be used to indicate exceptional conditions that a reasonable application might want to catch and recover from, whereas standard exceptions should be used to indicate exceptional conditions that are the result of a programming error or an unexpected condition that a reasonable application should not try to catch.

Here is an example of how you can create a custom exception called InvalidAgeException.

public class InvalidAgeException extends Exception {
    public InvalidAgeException() {
    }

    public InvalidAgeException(String message) {
        super(message);
    }

    public InvalidAgeException(String message, Throwable cause) {
        super(message, cause);
    }
}

In this example, the InvalidAgeException class extends the Exception class and it has three constructors:

  • A default constructor that takes no arguments.

  • A constructor that takes a string argument which represents the error message.

  • A constructor that takes a string argument and a Throwable argument, which represents the error message and the cause of the exception.

  • The first two constructors simply call the corresponding constructors in the Exception class, while the last one calls the super(message, cause) constructor in the Exception class to specify both a message and a cause for the exception.
Now you can use this custom exception in your code like this

int age = -5;
if (age < 0) {
    throw new InvalidAgeException("Invalid age: " + age);
}

You can also use it in a method signature, like this

public void setAge(int age) throws InvalidAgeException {
    if (age < 0) {
        throw new InvalidAgeException("Invalid age: " + age);
    }
    this.age = age;
}

This way, the code that calls this method should handle the exception, or it should propagate it to the caller method by adding the throws InvalidAgeException clause in the method signature.