Writing Custom Exceptions in Java: A Complete Guide
Java custom exception class example extending Exception
In Java, exception handling is key to building robust applications. While Java provides many built-in exceptions, sometimes you need to create custom exceptions to handle application-specific errors more clearly.
A custom exception is a user-defined exception class that extends either Exception
(for checked exceptions) or RuntimeException
(for unchecked exceptions). They allow developers to convey more meaningful error information.
When built-in exceptions do not clearly represent the problem.
For domain-specific error reporting.
To improve code readability and maintainability.
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class TestCustomException {
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above");
}
}
public static void main(String[] args) {
try {
validateAge(16);
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
class DataNotFoundException extends RuntimeException {
public DataNotFoundException(String message) {
super(message);
}
}
public class Demo {
public static void main(String[] args) {
throw new DataNotFoundException("Requested data is missing!");
}
}
✅ Always extend the appropriate base class (Exception
or RuntimeException
).
✅ Provide clear, descriptive messages.
✅ Keep them lightweight — only store necessary information.
✅ Document where and why they are thrown.
Improved code clarity.
Easier debugging.
Better alignment with business logic.
Fine-grained exception handling.
Custom exceptions in Java give developers a way to handle domain-specific problems with clarity and precision. By creating well-named, meaningful exceptions, you can make your codebase more maintainable and easier to debug.