Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A lambda passed to Stream.map needs to call a method that throws IOException. Engineers wrap it with try { ... } catch (IOException e) { throw new RuntimeException(e); } everywhere. What options do you weigh?

The java.util.function types do not declare checked exceptions, so a lambda passed to Stream.map must handle IOException itself. Rather than copying try-catch with RuntimeException everywhere, we can wrap in UncheckedIOException, the JDK's intended unchecked wrapper for IOException, and unwrap it at the boundary; write one small shared helper that adapts a throwing function; or use a plain loop when I/O and error handling dominate. Whatever we choose, we never swallow the exception or lose its cause.

Why this question is asked

Streams and checked exceptions are one of the most common friction points in Java. A team starts with a neat pipeline, adds a step that reads a file or calls a remote API, and suddenly every lambda grows a try-catch block that throws new RuntimeException(e). The code gets noisy, error handling becomes inconsistent, and callers can no longer catch IOException because it has been disguised. Interviewers ask this because the options involve real trade-offs, and because how we handle errors matters more than how short the code is. In this answer, we will see why the compiler rejects the lambda, look at the problems with the current pattern, and then weigh four options.

1Why the Lambda Does Not Compile

Stream.map takes a Function<T, R>, and Function's single abstract method is R apply(T t), which declares no checked exceptions. A lambda implements that method, so it is bound by the same rule as any method: it may not throw a checked exception that its signature does not declare. Files.readString declares throws IOException, so calling it directly in the lambda is a compile error.

Java
List<Path> paths = List.of(Path.of("a.txt"), Path.of("b.txt"));
List<String> texts = paths.stream()
.map(p -> Files.readString(p)) // compile error: unreported exception IOException
.toList();

2What Is Wrong With the Current Pattern

The team's fix is to wrap every call. It compiles, but it has costs that grow with the codebase.

Java
.map(p -> {
try {
return Files.readString(p);
} catch (IOException e) {
throw new RuntimeException(e); // generic type: callers cannot tell I/O failure apart
}
})
// Variations found in review:
// catch (IOException e) { return null; } swallowed: a null flows on
// catch (IOException e) { throw new RuntimeException(e.getMessage()); } cause and stack lost

The first problem is noise: five lines of handling around one line of logic, repeated in every pipeline. The second is that RuntimeException tells nobody what happened, so a caller who wants to retry on I/O errors must catch every runtime exception. And the copies drift: some swallow the exception, which turns a missing file into a null that fails much later, and some keep only the message, which loses the original stack trace. Those two variations are real bugs, not style issues.

3Option 1: UncheckedIOException, Unwrapped at the Boundary

The JDK has a dedicated wrapper for exactly this case: UncheckedIOException, added in Java 8. It takes an IOException as its cause, and its getCause() returns it typed as IOException. The JDK itself uses it, for example Files.lines throws it from the stream when reading fails. Using it gives callers a specific type to catch.

Java
List<String> readAll(List<Path> paths) throws IOException {
try {
return paths.stream()
.map(p -> {
try { return Files.readString(p); }
catch (IOException e) { throw new UncheckedIOException(e); }
})
.toList(); // exceptions surface here, at the terminal step
} catch (UncheckedIOException e) {
throw e.getCause(); // callers see the original IOException again
}
}

Notice the boundary. Inside the pipeline the exception travels unchecked, and at the method's edge it becomes a checked IOException again, so the method's contract stays honest. Also notice that streams are lazy, so the exception is thrown when the terminal operation, toList(), runs, not when map() is called.

4Option 2: One Shared Helper That Adapts a Throwing Function

To remove the repeated try-catch, we can define a functional interface that is allowed to throw IOException and a helper that converts it into a standard Function. The important rule is to keep this helper in one shared place, so every team uses the same wrapping and nobody writes a version that swallows errors.

Java
@FunctionalInterface
public interface IOFunction<T, R> {
R apply(T t) throws IOException; // a custom interface may declare checked exceptions
}
public final class Unchecked {
public static <T, R> Function<T, R> io(IOFunction<T, R> f) {
return t -> {
try { return f.apply(t); }
catch (IOException e) { throw new UncheckedIOException(e); }
};
}
}
List<String> texts = paths.stream().map(Unchecked.io(Files::readString)).toList();

The pipeline is back to one readable line, and the behaviour is consistent everywhere. Some libraries offer helpers like this, and some code uses a trick called a sneaky throw to rethrow checked exceptions without declaring them. That trick compiles, but it hides a checked exception from the compiler entirely, so callers cannot catch it by type, and it is best avoided in shared code.

5Option 3: A Plain Loop

Streams are not always the clearer tool. When most of the work is I/O and error handling, for example reading files, skipping ones that are missing, and logging the rest, a loop can say it more directly, and it can declare throws IOException naturally.

Java
List<String> readAll(List<Path> paths) throws IOException {
List<String> texts = new ArrayList<>(paths.size());
for (Path p : paths) {
try {
texts.add(Files.readString(p));
} catch (NoSuchFileException e) {
log.warn("skipping missing file {}", p); // a deliberate, visible decision
}
}
return texts; // other IOExceptions propagate unchanged
}
Step throughChoosing how to handle IOException in a pipeline
  1. Is the pipeline mostly I/O and error handling?
    YesUse a plain loop with throws IOExceptionNoKeep the stream
  2. Does the team already have a shared helper?
    YesUse it: map(Unchecked.io(...))NoAdd one helper in a shared module
  3. Wrap in UncheckedIOException, keep the causeNever return null or drop the cause
  4. Unwrap at the method boundaryRethrow getCause() as IOException

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

Here, different failures get different treatment, which would be awkward inside a lambda. There is no rule that pipelines must be streams; the goal is code whose error behaviour is obvious to the next reader.

6Follow-up questions

Why not just declare a custom functional interface everywhere instead of Function?

Because Stream.map and the other JDK APIs only accept the standard java.util.function types. A custom throwing interface is useful as the input to an adapter like Unchecked.io, but the stream still needs a plain Function in the end.

What happens with parallel streams?

An exception thrown in any worker thread is propagated to the thread that called the terminal operation, so the same try-catch around the terminal step works. Other elements may already have been processed or may still be running when it is thrown, so side effects in the pipeline should be safe to repeat or abandon.

Is it ever acceptable to catch and continue inside the lambda?

Yes, if continuing is a deliberate decision, for example mapping a failure to an Optional.empty() or a result object that records the error, so later steps can report it. What is not acceptable is silently returning null or discarding the exception without logging or recording it.

7Conclusion

In this answer, we saw that lambdas passed to Stream.map cannot throw IOException because the java.util.function types declare no checked exceptions. Wrapping in a generic RuntimeException everywhere is noisy and invites bugs like swallowed errors and lost causes. Better options are UncheckedIOException with unwrapping at the boundary, one shared helper that adapts a throwing function, or a plain loop when I/O dominates, always keeping the original cause.

What to say in the interviewAbout 90 seconds aloud

Open with

The root cause is that the java.util.function interfaces, like Function for map, declare no checked exceptions, so a lambda calling something that throws IOException has to handle it inside.

Then, if they want more

The team's pattern works but has real problems: it's noisy, RuntimeException tells callers nothing about what failed, and in review I usually find copies that return null or keep only the message, which swallow the error or lose the cause. So I weigh a few options.

First, wrap in UncheckedIOException, which is the JDK's intended unchecked wrapper for IOException and is what Files.lines uses itself, and then at the method boundary catch it and rethrow getCause, so the method can still declare throws IOException. Remember that streams are lazy, so it surfaces at the terminal operation.

Second, to remove the repeated try blocks, write one small helper: a functional interface that may throw IOException, and a static method that adapts it into a Function, so pipelines read map of Unchecked.io of Files::readString. It must live in one shared place so everyone wraps the same way. I'd avoid sneaky-throw tricks that hide checked exceptions from the compiler.

Third, if the code is mostly I/O and error handling, a plain for loop with throws IOException is often clearer, especially when different failures need different treatment. Whatever we pick, we never swallow the exception or lose its cause.

About this answer

Last updated
12 November 2026
Versions it names
Java 8
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 "A lambda passed to Stream.map needs to call a method that throws IOException. Engineers...": https://scrivio-interview-library.netlify.app/java/interfaces-and-abstract-classes/428190a815/