Sobes.tech
Senior

How to create a custom exception in Java?

sobes.tech AI

Answer from AI

In Java, to create a custom exception, you need to create a class that inherits from one of the exception classes, usually from Exception or RuntimeException. If you want to create a checked exception, inherit from Exception; if unchecked — from RuntimeException.

Example of creating a custom unchecked exception:

public class MyCustomException extends RuntimeException {
    public MyCustomException() {
        super();
    }

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

    public MyCustomException(String message, Throwable cause) {
        super(message, cause);
    }

    public MyCustomException(Throwable cause) {
        super(cause);
    }
}

Such an exception can be used to signal specific errors in your application, adding context and improving error handling.