Creating user-defined exceptions

In Java, we can create user-defined exceptions by extending the Exception class (or one of its subclasses like RuntimeException if we want to make an unchecked exception).

To create a user-defined exception, define a class that extends the Exception (for checked exceptions) or RuntimeException (for unchecked exceptions).

Example

InvalidAgeException is a user-defined checked exception. It takes a message that can be passed when the exception is thrown. To use this exception, we can throw it in our code where necessary, just like any other exception.

Output

In the above example, the checkAge() method throws the InvalidAgeException when the age is less than 18. The main method catches and handles this exception.