Java 21: Handle validation errors without exceptions for control flow. Compare exceptions, Optional and a sealed Result type with pattern matching.
Problem
Parse a sign-up form (email, age) into a validated Customer. Callers need to know why input is invalid, and with several fields, ideally all the errors at once.
record Customer(String email, int age) {}Approach 1: Exceptions (the classic way)
Simple to call, but exceptions for expected business outcomes are expensive (stack traces), easy to forget to catch, and they stop at the first error.
class InvalidInputException extends Exception {
InvalidInputException(String message) { super(message); }
}
class ParseWithExceptions {
static Customer parse(String email, String age) throws InvalidInputException {
if (email == null || !email.matches("[^@\\s]+@[^@\\s]+\\.[a-z]{2,}")) throw new InvalidInputException("invalid email");
int a;
try { a = Integer.parseInt(age); } catch (NumberFormatException e) { throw new InvalidInputException("age is not a number"); }
if (a < 18) throw new InvalidInputException("must be 18 or older");
return new Customer(email, a);
}
}Approach 2: Optional (concise, but loses the reason)
Great when absence needs no explanation; here the caller only learns "invalid".
import java.util.Optional;
class ParseWithOptional {
static Optional<Customer> parse(String email, String age) {
try { return Optional.of(ParseWithExceptions.parse(email, age)); }
catch (InvalidInputException e) { return Optional.empty(); }
}
}Approach 3: Sealed Result type + pattern matching for switch (Java 21)
The return type tells the caller that failure is possible, carries the reason, composes with map/flatMap, and the compiler forces callers to handle both cases.
import java.util.function.Function;
sealed interface Result<T> permits Ok, Err {
static <T> Result<T> ok(T value) { return new Ok<>(value); }
static <T> Result<T> err(String error) { return new Err<>(error); }
default <R> Result<R> map(Function<T, R> f) {
return switch (this) {
case Ok<T>(T value) -> new Ok<>(f.apply(value));
case Err<T>(String error) -> new Err<>(error);
};
}
default <R> Result<R> flatMap(Function<T, Result<R>> f) {
return switch (this) {
case Ok<T>(T value) -> f.apply(value);
case Err<T>(String error) -> new Err<>(error);
};
}
}
record Ok<T>(T value) implements Result<T> {}
record Err<T>(String error) implements Result<T> {}
class ParseWithResult {
static Result<String> email(String raw) {
return raw != null && raw.matches("[^@\\s]+@[^@\\s]+\\.[a-z]{2,}") ? Result.ok(raw.toLowerCase()) : Result.err("invalid email");
}
static Result<Integer> age(String raw) {
try {
int a = Integer.parseInt(raw);
return a >= 18 ? Result.ok(a) : Result.err("must be 18 or older");
} catch (NumberFormatException e) {
return Result.err("age is not a number");
}
}
static Result<Customer> parse(String email, String age) {
return email(email).flatMap(e -> age(age).map(a -> new Customer(e, a))); // stops at the first error
}
}Approach 4: Accumulate every error (best UX for forms)
Validate each field independently and collect all messages, so the user fixes everything in one go.
import java.util.ArrayList;
import java.util.List;
class ParseAllErrors {
sealed interface Validation permits Valid, Invalid {}
record Valid(Customer customer) implements Validation {}
record Invalid(List<String> errors) implements Validation {}
static Validation parse(String email, String age) {
Result<String> e = ParseWithResult.email(email);
Result<Integer> a = ParseWithResult.age(age);
if (e instanceof Ok<String>(String okEmail) && a instanceof Ok<Integer>(Integer okAge)) {
return new Valid(new Customer(okEmail, okAge));
}
List<String> errors = new ArrayList<>();
if (e instanceof Err<String>(String msg)) errors.add("email: " + msg);
if (a instanceof Err<Integer>(String msg)) errors.add("age: " + msg);
return new Invalid(List.copyOf(errors));
}
}
class ResultDemo {
static String render(Result<Customer> r) {
return switch (r) { // compiler checks both cases are handled
case Ok<Customer>(Customer c) -> "created " + c;
case Err<Customer>(String error) -> "rejected: " + error;
};
}
public static void main(String[] args) {
System.out.println(render(ParseWithResult.parse("Asha@Example.com", "30"))); // created Customer[email=asha@example.com, age=30]
System.out.println(render(ParseWithResult.parse("asha@example.com", "15"))); // rejected: must be 18 or older
System.out.println(ParseWithOptional.parse("bad", "30")); // Optional.empty
try { ParseWithExceptions.parse("bad", "x"); } catch (InvalidInputException e) { System.out.println("exception: " + e.getMessage()); }
System.out.println(switch (ParseAllErrors.parse("bad", "x")) {
case ParseAllErrors.Valid(Customer c) -> "ok " + c;
case ParseAllErrors.Invalid(var errors) -> "errors " + errors; // [email: invalid email, age: age is not a number]
});
}
}Feasible → optimal
- Exceptions: fine for truly exceptional situations (I/O failures, bugs); costly and implicit for expected validation outcomes.
Optional: when the reason does not matter.- Sealed
Resultwith exhaustive switches: explicit, composable, cheap; best for domain operations whose failures are part of the contract. - Error accumulation: best user experience for forms. In Spring MVC, Bean Validation already accumulates field errors at the API boundary; use
Resulttypes inside the domain.
Follow-up questions interviewers ask
Try answering each one before you open it.
Can you use generic record patterns like `case Ok<T>(T value)` safely?
Yes. Java 21 checks generic record patterns against the static type: inside Result<T>, case Ok<T>(T value) is known to be safe without unchecked casts, and the compiler can infer type arguments, so case Ok(var value) also works. Exhaustiveness is checked against the sealed permits list.
When are exceptions still the right choice?
For failures the immediate caller cannot sensibly handle (database down, programming errors, broken invariants) and in frameworks built around them (Spring's transaction rollback, @ControllerAdvice mapping to HTTP errors). A common split: Result types for expected business outcomes inside the domain, exceptions for infrastructure failures, translated to HTTP responses at the edge.