A custom exception is a user-defined class that extends the Exception or Runtime.
Itβs used to signal specific, meaningful errors in your application.
Example
class class AgeTooLowException extends Exception {
public AgeTooLowException(String message) {
super(message);
}
}
void validateAge(int age) throws AgeTooLowException {
if (age < 18) {
throw new AgeTooLowException("Age must be 18 or above.");
}
}
class InvalidUsernameException extends RuntimeException {
public InvalidUsernameException(String message) {
super(message);
}
}
When to Use Custom Exceptions
- To represent domain-specific errors.
- To provide clearer error messages.
- To simplify debugging and logging.
- To enforce business rules (e.g. InsufficientBalanceException).
Best Practices
- Inherit from Exception or RuntimeException.
- Include constructors with message + cause.
- Name them clearly: end with Exception.
Real-World Analogy
Javaβs build-in exceptions = road signs.
Custom exceptions = your own business-specific warnings.
Tip
Be ready to explain:
- why and when youβd use a custom exception,
- checked and unchecked choice,
- how custom exceptions improve code readability and maintainability.
Parent: _Exceptions