Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What are the options for handling errors in a functional style in Java, instead of throwing exceptions from inside lambdas?

Instead of throwing from inside lambdas, we can return Optional when the only failure is absence, return a result type such as a sealed interface Result<T> with Success and Failure records when the caller needs to know what went wrong, use CompletableFuture's exceptionally or handle for asynchronous code, and wrap checked exceptions in unchecked ones at the lambda boundary when a failure should simply stop the pipeline. The choice depends on whether the caller should recover from the error.

Why this question is asked

Lambdas and streams changed how we write Java, but exceptions did not change with them. Functional interfaces such as Function cannot throw checked exceptions, a single exception in a stream aborts the whole pipeline, and in asynchronous code an exception thrown on another thread does not reach a try block in the caller. Interviewers ask this question to see whether we know the alternatives and, more importantly, how to choose between them. In this answer, we will look at why exceptions are awkward inside lambdas, then go through the four options with code, and finish with how to choose.

1Why Exceptions Are Awkward Inside Lambdas

Two things make exceptions awkward in functional code. First, the standard functional interfaces do not declare checked exceptions, so a lambda that calls a method throwing IOException does not compile when passed to map. Second, even unchecked exceptions are blunt in a stream: the first one stops the whole pipeline, so one bad element out of ten thousand loses all the results.

Java
List<Path> files = List.of(Path.of("a.txt"), Path.of("missing.txt"), Path.of("c.txt"));
files.stream().map(Files::readString).toList();
// does not compile: unreported exception IOException
List.of("1", "x", "3").stream().map(Integer::parseInt).toList();
// NumberFormatException: For input string: "x"; the results for "1" and "3" are lost

So we need ways to express failure as a value, or to decide deliberately that a failure should stop everything.

2Option 1: Return Optional When the Only Failure Is Absence

If the only thing that can go wrong is "there is no result", and the caller does not need to know why, Optional is the simplest choice. Parsing user input is a typical example.

Java
static Optional<Integer> tryParse(String s) {
try {
return Optional.of(Integer.parseInt(s));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
List.of("1", "x", "3").stream()
.map(Main::tryParse)
.flatMap(Optional::stream)
.toList(); // [1, 3]: the bad value is skipped

Notice what we gave up: the reason. If the caller needs to report which inputs failed and why, Optional is not enough.

3Option 2: Return a Result Type

A result type holds either a success value or a description of the failure. Modern Java makes this easy with a sealed interface and two records, and pattern matching handles both cases with the compiler checking that neither is forgotten.

Java
sealed interface Result<T> {
record Success<T>(T value) implements Result<T> {}
record Failure<T>(String input, String error) implements Result<T> {}
}
static Result<Integer> parse(String s) {
try {
return new Result.Success<>(Integer.parseInt(s));
} catch (NumberFormatException e) {
return new Result.Failure<>(s, "not a number");
}
}
List<Result<Integer>> results = List.of("1", "x", "3").stream().map(Main::parse).toList();
for (Result<Integer> r : results) {
switch (r) {
case Result.Success<Integer> s -> System.out.println("ok " + s.value());
case Result.Failure<Integer> f -> System.out.println("bad " + f.input() + ": " + f.error());
}
}
// ok 1
// bad x: not a number
// ok 3

Every element produces a result, the pipeline completes, and the caller can process the successes and report the failures, for example in an import that shows the user which rows to fix. Libraries such as Vavr offer ready-made types like Try and Either for the same purpose, but a small sealed type in our own code is often enough and needs no extra dependency.

4Option 3: CompletableFuture's exceptionally and handle

In asynchronous code, the work runs on another thread, so a try block around the call that starts it cannot catch its failure. CompletableFuture carries the failure inside the future instead, and offers methods to deal with it when it completes.

Java
CompletableFuture<Rate> rate = CompletableFuture
.supplyAsync(() -> client.fetchRate("EUR")) // may throw on another thread
.exceptionally(ex -> Rate.FALLBACK); // replaces a failure with a value
CompletableFuture<String> status = CompletableFuture
.supplyAsync(() -> client.fetchRate("EUR"))
.handle((r, ex) -> ex == null
? "rate " + r
: "unavailable: " + ex.getCause().getMessage()); // sees both outcomes

exceptionally runs only on failure and must return a replacement value, while handle runs on both success and failure and receives both, one of them null. Notice getCause(): the exception passed to these methods is usually a CompletionException wrapping the original, so the real error is its cause. whenComplete is a third option that observes the outcome, for logging for example, without changing it.

5Option 4: Wrap Checked Exceptions When Failure Should Stop

Sometimes failing fast is exactly right. If a configuration file is missing, there is nothing useful to do with the other files. Then we wrap the checked exception in an unchecked one at the lambda boundary and let it stop the pipeline.

Java
List<String> contents = files.stream()
.map(p -> {
try {
return Files.readString(p);
} catch (IOException e) {
throw new UncheckedIOException("cannot read " + p, e); // keeps the cause
}
})
.toList();
// UncheckedIOException: cannot read missing.txt

The wrapper keeps the original exception as its cause, so nothing is lost in the logs. UncheckedIOException exists in the JDK for exactly this case. If this pattern repeats, a small helper that turns a throwing function into a Function keeps the lambdas short, but it should still wrap, never silently swallow, the exception.

6Choosing Between the Options

The deciding question is whether the caller should recover from the error. If failure only means "no value" and the reason does not matter, Optional is the simplest. If the caller needs to know what failed so it can report or retry, a result type keeps that information. If the work is asynchronous, CompletableFuture's methods are the natural tools. And if failure means the whole operation cannot continue, wrapping and throwing is the honest choice, because pretending to continue would hide a real problem.

Step throughWhich error-handling option to use
  1. Should the caller recover?
    YesContinueNoWrap and throw unchecked
  2. Is the work asynchronous?
    Yesexceptionally or handleNoContinue
  3. Does the caller need the reason?
    YesReturn a Result typeNoReturn Optional

3 steps in order. Play them, or step through them one at a time.

Start from what the caller must do with the failure, not from the technique.

7Follow-up questions

Is it bad to catch an exception and return Optional.empty()?

It is fine when the exception only means "no result", like a parse failure on user input. It is bad when it hides real problems, such as catching a database exception and returning empty, which makes an outage look like missing data.

What is the difference between handle and whenComplete?

Both see the result and the exception. handle returns a new value, so it can turn a failure into a success. whenComplete returns the original outcome unchanged, so it is used for side effects like logging or metrics.

Why not use sneaky throws to rethrow checked exceptions without wrapping?

Tricks that throw a checked exception without declaring it compile, but they surprise callers, who cannot catch an exception the compiler says is never thrown. Wrapping in an unchecked exception with the cause is explicit and safe.

8Conclusion

In this answer, we saw that exceptions are awkward inside lambdas because functional interfaces cannot throw checked exceptions and one failure aborts a whole stream. Optional fits when the only failure is absence, a sealed Result type with Success and Failure records fits when the caller needs the reason, CompletableFuture's exceptionally and handle fit asynchronous code, and wrapping checked exceptions in unchecked ones fits when failure should stop the pipeline. The choice depends on whether, and how, the caller should recover.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem with exceptions in lambdas is twofold: functional interfaces like Function can't throw checked exceptions, so something like map(Files::readString) doesn't compile, and an unchecked exception aborts the whole stream, so one bad element loses every result.

Then, if they want more

There are four main options, and I pick based on whether the caller should recover. If the only failure is absence and the reason doesn't matter, I return Optional; for example a tryParse that returns empty for bad input, then flatMap with Optional::stream to skip failures. If the caller needs to know what failed, I return a result type.

In modern Java that's a sealed interface Result with Success and Failure records, and a switch handles both cases with the compiler checking I didn't forget one. That's good for imports where you report bad rows. Vavr's Try or Either does the same if a team already uses it.

For async code, CompletableFuture carries the failure: exceptionally replaces it with a fallback value, handle sees both outcomes and maps them to a result, and I remember the exception is usually a CompletionException, so I look at the cause.

Finally, if a failure means the whole operation can't continue, I wrap the checked exception in an unchecked one, like UncheckedIOException, at the lambda boundary, keeping the cause, and let it stop the pipeline.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What are the options for handling errors in a functional style in Java, instead of...": https://scrivio-interview-library.netlify.app/java/functional-design/df9bb8465d/