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());
}
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.