Coding⏱️ 2 min read📅 2026-05-31

How to Fix: How to create a custom exception type in Java?

Create a custom exception in Java by extending the Exception class and providing a meaningful error message.

Quick Answer: Extend the Exception class and provide a constructor with a descriptive error message, e.g., throw new CustomException("Invalid input");

To create a custom exception in Java, you need to extend the built-in Exception class. This is because custom exceptions must be subclasses of an existing exception type.

✅ Best Solutions to Fix It

Method 1: Extending the Exception Class

  1. Step 1: Create a new class that extends Exception, e.g., InvalidWordException.

Method 2: Creating a Custom Exception Class

  1. Step 1: Create a new class that extends Exception, e.g., InvalidWordException.java with the following code:
// InvalidWordException.java
public class InvalidWordException extends Exception {
public InvalidWordException(String message) {
super(message);
}

✨ Wrapping Up

To throw your custom exception, use the throw new keyword followed by an instance of your custom exception class. For example:

// Throw the custom exception
if(word.contains(

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions