Custom Exception Hierarchy
Defines a custom exception hierarchy with domain-specific exceptions, demonstrating proper exception chaining, message formatting, and multi-catch handling.
Code
public class CustomExceptions {
static class DomainException extends Exception {
public DomainException(String message, Throwable cause) {
super(message, cause);
}
}
static class ValidationException extends DomainException {
public ValidationException(String message) {
super(message, null);
}
}
static class NotFoundException extends DomainException {
public NotFoundException(String id) {
super("Resource not found: " + id, null);
}
}
static void validateAge(int age) throws ValidationException {
if (age < 0 || age > 150) {
throw new ValidationException("Invalid age: " + age);
}
}
static String findUser(String id) throws NotFoundException {
if (!"admin".equals(id)) {
throw new NotFoundException(id);
}
return "Administrator";
}
public static void main(String[] args) {
try {
validateAge(200);
findUser("guest");
} catch (ValidationException | NotFoundException e) {
System.err.println("Error: " + e.getMessage());
}
}
}What the code does
Custom Exception Hierarchy keeps everything in the classes CustomExceptions, DomainException, ValidationException and NotFoundException and the functions DomainException, ValidationException, NotFoundException and main.
Invalid states are rejected up front: it throws ValidationException and NotFoundException instead of continuing with bad data.
Applying it
The entry-point signature is public DomainException(String message, Throwable cause)
Statements that matter
throw new ValidationException("Invalid age: " + age);
throw new NotFoundException(id);
return "Administrator";
Interactive Tools for This Topic
FAQ
- What happens on invalid input?
- The code throws `ValidationException` and `NotFoundException`. Handle it at the call site or let it propagate deliberately.
- How do you run Custom Exception Hierarchy?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.