Java / Java 21 Coding Standards Interview Questions
Which is better and why: exceptions versus sealed result types for error handling?
| Exceptions | Sealed result type |
| Failure path is implicit; easy for a caller to forget to catch it. | Failure is a value the caller must explicitly handle to get the success value out. |
| Carries a stack trace, useful for unexpected/bug-like failures. | No stack trace by default; best for expected, frequent outcomes. |
| Cheap to write for rare failure paths. | More ceremony per call site, but exhaustiveness is compiler-checked. |
sealed interface Result<T> permits Success, Failure {} record Success<T>(T value) implements Result<T> {} record Failure<T>(String reason) implements Result<T> {}
Exceptions remain the better fit for failures that are genuinely exceptional - a database being unreachable, a bug in caller code - where a stack trace and unwinding the call stack are exactly what is needed and where the failure is not expected on a normal, successful path.
A sealed Result type is the better fit for expected, frequent outcomes on the normal path - a validation failure, a not-found lookup - because a switch over the sealed result forces the caller to handle both branches at compile time, whereas an exception can always be silently un-caught and never actually forces anything.
More Related questions...