How do I model parsing success and failure with a sealed interface in Java 21?

When a user enters a number, your program needs to handle both valid and invalid input. Returning null on failure loses the reason for the error. Instead, you can return an object that represents either a parsed value or a helpful message.

This tutorial builds a small result model using a sealed interface, two records, and a pattern-matching switch.

1. Define the possible outcomes

Our parser returns a ParseResult. Its sealed declaration lists exactly two permitted implementations:

  • Success, containing an integer.
  • Failure, containing an error message.

This makes the possible outcomes visible in the type definitions.

2. Parse input at the application boundary

Before parsing, check for null or blank input. For other strings, remove surrounding whitespace and call Integer.parseInt().

Catch NumberFormatException inside the parser and convert it into a Failure. The caller can then handle both outcomes through the same return type.

3. Handle each outcome with a switch

A record pattern such as Success(int value) extracts the component into a local variable. Java 21 supports record patterns in switches. See Java’s record pattern documentation.

Because the switch covers both permitted implementations, it needs no default. If you later add another result type, recompiling this switch helps reveal the missing case. See pattern matching for switch.

4. Run the complete example

Save this code as ParseResultExample.java:

public class ParseResultExample {
    sealed interface ParseResult permits Success, Failure { }

    record Success(int value) implements ParseResult { }

    record Failure(String message) implements ParseResult { }

    static ParseResult parse(String input) {
        if (input == null || input.isBlank()) {
            return new Failure("Enter a whole number");
        }

        try {
            return new Success(Integer.parseInt(input.strip()));
        } catch (NumberFormatException exception) {
            return new Failure("Invalid or out-of-range integer");
        }
    }

    static String describe(ParseResult result) {
        return switch (result) {
            case Success(int value) -> "Parsed: " + value;
            case Failure(String message) -> "Error: " + message;
        };
    }

    public static void main(String[] args) {
        String[] inputs = {
                " 42 ", "hello", "2147483648", null
        };

        for (String input : inputs) {
            System.out.println(describe(parse(input)));
        }
    }
}

Compile and run:

javac --release 21 ParseResultExample.java
java ParseResultExample

Output:

Parsed: 42
Error: Invalid or out-of-range integer
Error: Invalid or out-of-range integer
Error: Enter a whole number

The third input contains valid digits but exceeds the maximum int value, 2147483647. It therefore follows the same failure path as invalid text. The accepted range and exception behavior are documented in Integer.parseInt().

Best practices

  • Return a result object for every expected outcome; keep null out of the result contract.
  • Catch the specific parsing exception rather than a broad Exception.
  • Use separate failure types when callers need different recovery actions.
  • Keep presentation separate from parsing, as the describe() method does here.
  • Remember that default does not handle a null switch selector. This parser always returns a non-null result.

Summary

A sealed result model makes success and failure explicit. Records carry the associated data, while an exhaustive switch gives callers a clear place to handle every outcome.