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
|
1 2 3 4 5 6 7 |
// Custom checked exception class InvalidAgeException extends Exception { // Constructor to pass error message public InvalidAgeException(String message) { super(message); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Test { public static void main(String[] args) { try { checkAge(15); } catch (InvalidAgeException e) { System.out.println("Error: " + e.getMessage()); } } public static void checkAge(int age) throws InvalidAgeException { if (age < 18) { throw new InvalidAgeException("Age must be 18 or older."); } else { System.out.println("Age is valid."); } } } |
Output
|
1 |
Error: Age must be 18 or older. |
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.