Custom Exceptions in Java allow developers to create their own exception classes to represent specific error conditions in an application. They improve code readability, error handling clarity, and make debugging easier.
Exception or RuntimeExceptionTo create a custom exception, define a class that extends Exception (checked) or RuntimeException (unchecked). Provide constructors to pass error messages to the parent class.
// Custom checked exception definition
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
// Demonstrates throwing and catching a custom exception
class TestAge {
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above");
}
System.out.println("Valid age");
}
public static void main(String[] args) {
try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
}
Age must be 18 or above
The custom exception is thrown when the age is below 18. The catch block handles it gracefully and displays a meaningful message.
Enter an age below to simulate the Java logic in real-time. If you enter less than 18, the simulator will "throw" and "catch" the custom exception.