Steps to Create Custom Exception in Java

Creating a custom exception in Java is a straightforward process. In this guide, we will see step-by-step how to create custom exceptions in Java.

Steps to Create a Custom Exception in Java

1. Decide the Exception Type: 

Decide whether your exception should be checked or unchecked.

Checked Exceptions: These are the exceptions that a method can throw but cannot handle on its own. Any method that might throw a checked exception must either handle it using a try-catch block or declare it using the throws keyword. 

Unchecked Exceptions: These are the exceptions that can be thrown during the execution of the program but were not anticipated. They extend RuntimeException and don't need to be declared or caught. 

2. Choose a Meaningful Name: 

Your custom exception name should typically end with "Exception" to maintain clarity and adhere to Java's naming convention. 

For example:

ResourceNotFoundException

BadRequestException

AgeValidatorException

BlogAPIException

3. Extend the Appropriate Exception Class: 

For checked exceptions, extend the Exception class. 

For unchecked exceptions, extend the RuntimeException class. 

4. Create Constructors: 

To give more context or customization ability to your exception, create constructors for it. At a minimum, you should provide: 

  • A default constructor. 
  • A constructor that takes a string parameter for the error message. 
  • Additional constructors as required (e.g., to initialize custom fields). 

5. (Optional) Add Custom Fields and Methods: 

If you want your exception to hold additional information or provide specific functionalities, you can add custom fields and methods. 

Now, let's see how to use the above step to create custom-checked exceptions and custom-unchecked exceptions.

Create a Checked Custom Exception

Let's create a checked custom exception named InvalidOrderException:

public class InvalidOrderException extends Exception {

    public InvalidOrderException() {
        super("The order is invalid");
    }

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

Create a Custom Unchecked Exception

public class OrderConfigurationException extends RuntimeException {

    public OrderConfigurationException() {
        super("Configuration of the order is incorrect");
    }

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

Using Custom Exceptions

You can throw your custom exception just like any other exception using the throw statement.

public class OrderProcessor {

    public void validateOrder(Order order) throws InvalidOrderException {
        if(order == null || order.getItems().isEmpty()) {
            throw new InvalidOrderException("Order is empty or null");
        }
    }

    public void configureOrder(Order order) {
        if(order.getConfiguration() == null) {
            throw new OrderConfigurationException("Order lacks necessary configuration");
        }
    }
}

Usage

For the checked exception (InvalidOrderException), you'll either need to catch it or declare that your method may throw it:

public static void main(String[] args) {
    OrderProcessor processor = new OrderProcessor();
    try {
        processor.validateOrder(null);  // This will throw InvalidOrderException
    } catch (InvalidOrderException e) {
        System.out.println("Error: " + e.getMessage());
    }

    processor.configureOrder(new Order());  // This will throw OrderConfigurationException
}

Best Practices to Create Custom Exceptions in Java

Descriptive Naming: Ensure the name of the exception class clearly indicates its purpose. Always end with "Exception", e.g., InvalidInputException

Extend the Right Class: 
  • For checked exceptions, extend the Exception class. 
  • For unchecked exceptions, extend the RuntimeException class. 
Provide Useful Constructors: Offer standard constructors such as one with no parameters, one with a String message, and one that accepts a Throwable cause. 
public class CustomException extends Exception {
    public CustomException() { super(); }
    public CustomException(String message) { super(message); }
    public CustomException(String message, Throwable cause) { super(message, cause); }
    public CustomException(Throwable cause) { super(cause); }
}
Document Properly: Use JavaDoc to detail when the custom exception might be thrown and explain any additional fields or context it provides. 

Make Custom Exceptions Immutable: Once created, exceptions should be immutable to ensure thread safety. Avoid setters in exception classes. 

Add Relevant Information: Your custom exception can have additional fields that provide more information about the error. For instance, an OrderNotFoundException might contain an orderId field.

These are concise but integral guidelines to follow when creating custom exceptions in Java. They ensure that your custom exceptions are robust, maintainable, and consistent with Java's exception-handling standards.

Comments