How do I create a custom exception in Java?

You can create a custom exception to describe a problem specific to your application. Give it a meaningful name so calling code can recognize and handle the problem.

In this example, you will create an InvalidAgeException and throw it when someone under 18 tries to register.

Source code

Save the following code as CustomExceptionExample.java:

public class CustomExceptionExample {
    void main() {
        try {
            register(16);
        } catch (InvalidAgeException exception) {
            IO.println("Registration failed: " + exception.getMessage());
        }

        IO.println("The program continues.");
    }

    void register(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException(
                    "You must be at least 18 years old.");
        }

        IO.println("Registration successful.");
    }
}

class InvalidAgeException extends Exception {
    InvalidAgeException(String message) {
        super(message);
    }
}

Explanation

The custom exception extends Exception:

class InvalidAgeException extends Exception {
    InvalidAgeException(String message) {
        super(message);
    }
}

This makes InvalidAgeException a checked exception. Code that calls a method declaring this exception must either catch it or declare that it can propagate it.

The constructor accepts a message and passes it to the superclass constructor:

super(message);

Calling code can retrieve that message using getMessage().

Declaring the exception

The register() method declares the exception using throws:

void register(int age) throws InvalidAgeException {

This declaration tells callers that the method may throw an InvalidAgeException.

Throwing the exception

The method checks whether the age meets the registration requirement:

if (age < 18) {
    throw new InvalidAgeException(
            "You must be at least 18 years old.");
}

The throw statement creates and throws the exception. Execution leaves the method immediately, so the success message is skipped.

Notice the difference between the two keywords:

Keyword Purpose
throw Throws a specific exception object
throws Declares exceptions that a method may propagate

Handling the exception

The calling code catches the custom exception:

try {
    register(16);
} catch (InvalidAgeException exception) {
    IO.println("Registration failed: " + exception.getMessage());
}

Since 16 is below the minimum age, the catch block prints the failure message.

Once the exception is handled, the program continues after the try-catch statement.

Run the example

Compile and run the file:

javac CustomExceptionExample.java
java CustomExceptionExample

Output

Registration failed: You must be at least 18 years old.
The program continues.

If you change the method call to register(20), the output becomes:

Registration successful.
The program continues.

Choosing an exception type

Extend Exception when you want callers to catch or declare the exception. Extend RuntimeException when you want an unchecked exception, which callers are not required to catch or declare.

Use a custom exception when its name gives callers useful information or lets them handle a specific failure separately. For a simple invalid argument, a standard exception such as IllegalArgumentException may be sufficient.

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.