Custom exceptions in Java allow you to create specific error types that are more meaningful for your application. You can define your own exception by extending the `Exception` class for checked exceptions or `RuntimeException` for unchecked exceptions.
Here’s how you can create a custom exception:
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class TestCustomException {
public static void main(String[] args) {
try {
checkAge(15);
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is not valid");
}
}
}
This example creates a custom exception `InvalidAgeException` that is thrown when the age is less than 18. Custom exceptions improve code readability and help in handling specific error cases more effectively.
Leave a Reply