How to Create Custom Exception in Java

Custom Exception :

In Java, we can create custom exceptions by extending the built-in Exception class or one of its subclasses. For creating a custom exception in java we have to follow the process below :

Create a Custom Exception Class:

public class CustomException extends Exception {
    public CustomException() {
        super();
    }

    public CustomException(String message) {
        super(message);
    }
}
Throwing the Custom Exception:

After creating the custom exception , then we can use the custom exception in our code for handling the exception.
public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            int value = 10;
            if (value > 5) {
                throw new CustomException("Value is too high");
            }
        } catch (CustomException e) {
            System.out.println("Caught custom exception: " + e.getMessage());
        }
    }
}
custom exception best practices :

1. It's a good practice to provide both a default (parameterless) constructor and a constructor with a message parameter in your custom exception class.

2. Name your custom exceptions with descriptive names that reflect the nature of the problem they represent.

3. When throwing exceptions, make sure to include relevant error messages that provide useful information about the exception's cause.
Next Post Previous Post
No Comment
Add Comment
comment url