Creating a custom Exception class in Java

Java provides many subclasses of the Exception class that should be enough to handle all general exceptions that may happen when a Java application is running.

Still, there may be times when you need to create a custom exception that is specific to your application logic.

To create a custom exception in Java, you need to extend the default Exception class which is the superclass of all Java exception types.

Let’s see an example of throwing a custom exception when a string doesn’t contain a certain word.

In this scenario, the myString variable needs to contain the word Java or you need to throw a custom exception named InvalidStringException.

First, create the InvalidStringException class that extends the Exception class. The class needs to have at least one constructor that accepts the errorMessage as shown below:

class InvalidStringException extends Exception {
    public InvalidStringException(String errorMessage) {
        super(errorMessage);
    }
}

Once you have the custom exception class, the next step is to throw the custom exception in your code.

The easiest example looks like this:

class Main {
    public static void main(String[] args) 
            throws InvalidStringException {
        String myString = "Programming Language";
        if (!myString.contains("Java")) {
            throw new InvalidStringException(
                "myString must contain the word Java"
            );
        }
    }
}

When you run the code, the following error will be thrown in your Java console:

Exception in thread "main" InvalidStringException: 
myString must contain the word Java

But it’s obvious that the if block above will always throw the custom exception because of the initialized value.

To make the code more realistic, you can add the custom exception to a static method in your class as follows:

class Main {
    public static void main(String[] args) 
            throws InvalidStringException {
        String myString = "Programming Language";
        checkString(myString);
    }

    static void checkString(String test)
            throws InvalidStringException {
        if(!test.contains("Java")) {
            throw new InvalidStringException(
                "myString must contain the word Java"
            );
        }
    }
}

With the above code, your checkString() method can be called to check different String variables, and the InvalidStringException is used to throw a custom exception when the required condition is fulfilled.

A custom exception can be handled with a try...catch block just like built-in Java exceptions.

In the code below, a try...catch block is used to surround the call to the checkString() method:

String myString = "Programming Language";
try {
    checkString(myString);
} catch (Exception e) {
    System.out.println("Invalid String:");
    System.out.println(e.getMessage());
}

Instead of throwing an error and stopping the program, Java will simply output the error log to the console:

Invalid String:
myString must contain the word Java

Process finished with exit code 0

Java allows you to extend both checked and unchecked exceptions in your source code.

Checked exceptions extend the Exception class, while unchecked exceptions extend the RuntimeException class.

And that’s how you can create a custom exception in the Java programming language. 😉

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.