Course Content
Core Java
About Lesson

In Java, creating custom exception classes allows you to define application-specific error conditions that are not covered by the standard Java exceptions. Custom exceptions make your code more readable and help in identifying the precise cause of errors in complex applications.

Benefits of using Custom Exception

  • Readability: Custom exceptions can make your code more understandable.
  • Specificity: They allow you to handle specific error conditions in your application.
  • Maintainability: They make it easier to manage and handle errors, improving overall code maintainability.
  • Chaining Exceptions: Use the constructor with a cause to maintain the stack trace.
  • Specific Messages: Provide detailed error messages to make debugging easier.

Steps to create Custom Exception

We can create our own exception by extending Exception class.

  1. Define a class : Extend the Exception class for checked exceptions or RuntimeException for unchecked exceptions.
// Custom checked exception
public class InvalidAgeException extends Exception {
    // Default constructor
    public InvalidAgeException() {
        super("Invalid age provided");
    }

    // Constructor that accepts a message
    public InvalidAgeException(String message) {
        super(message);
    }

    // Constructor that accepts a message and a cause
    public InvalidAgeException(String message, Throwable cause) {
        super(message, cause);
    }
}
  1. Constructors: Implement constructors for the custom exception.
    1. Default Constructor: Provides a default error message.
    2. Parameterized Constructor: Accepts a custom error message.
  2. Override Methods (optional): Override methods like toString() to provide more information about the exception.
  3. Use the Custome Exception in code
public class CustomUncheckedExceptionExample {
    public static void main(String[] args) {
        try {
            validateScore(-5); // This will throw an InvalidScoreException
        } catch (InvalidScoreException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }

    public static void validateScore(int score) {
        if (score < 0) {
            throw new InvalidScoreException("Score cannot be negative.");
        }
        System.out.println("Valid score: " + score);
    }
}

Scroll to Top