Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Make this compile and keep the IOException visible to the caller:

Java
List<String> contents = paths.stream().map(p -> Files.readString(p)).toList();

It does not compile because Function.apply declares no checked exceptions, so a lambda passed to map cannot throw IOException. To keep the IOException visible to the caller, the simplest option is a plain for loop in a method that throws IOException. Inside a stream, we can wrap it in UncheckedIOException and unwrap it at the caller, or define a ThrowingFunction interface with a helper that does the wrapping. We must never swallow the exception or return null.

Why this question is asked

Reading files, calling remote services and parsing input all throw checked exceptions, and sooner or later we want to do one of those inside a stream. The compiler refuses, and the quick fixes people reach for, catching and printing, or returning null, hide real failures. Interviewers ask this small coding question because the answer shows whether we understand how checked exceptions and functional interfaces interact, and whether we care about failures reaching the right place. In this answer, we will see exactly why the code does not compile, then write three correct versions and compare them, and finish with the versions we must avoid.

1Why the Code Does Not Compile

A checked exception is an exception that the compiler forces us to handle: every method that can throw it must either catch it or declare it with throws. IOException is checked, and Files.readString(Path) declares throws IOException.

Stream.map takes a Function<T, R>, whose only method is R apply(T t), with no throws clause. A lambda is the body of that apply method, so it may only throw what apply declares, which is no checked exceptions at all.

Java
List<String> contents = paths.stream()
.map(p -> Files.readString(p))
.toList();
// error: unreported exception IOException; must be caught or declared to be thrown

Notice that declaring throws IOException on our own method does not help. The exception would be thrown inside apply, and apply is not allowed to throw it, so the compiler stops at the lambda, not at our method.

2Option 1: A Plain Loop

When the caller needs to see IOException, the most direct answer is a for loop. There is no lambda in between, so the exception travels up through our method's own throws clause.

Java
static List<String> readAll(List<Path> paths) throws IOException {
List<String> contents = new ArrayList<>(paths.size());
for (Path p : paths) {
contents.add(Files.readString(p)); // IOException propagates as it is
}
return List.copyOf(contents); // unmodifiable, like toList()
}
readAll(List.of(Path.of("a.txt"), Path.of("missing.txt")));
// java.nio.file.NoSuchFileException: missing.txt (a subclass of IOException)

This is not a step backwards. For a short pipeline whose main job is I/O, a loop is clearer than any wrapping trick, it stops at the first failure, and the compiler checks every caller. The List.copyOf at the end keeps the result unmodifiable, just as toList() would.

3Option 2: Wrap in UncheckedIOException and Unwrap at the Caller

If we want to keep the stream, we catch the checked exception inside the lambda and rethrow it wrapped in an unchecked one. The JDK provides UncheckedIOException exactly for this purpose. Then, at the boundary of our method, we unwrap it and rethrow the original IOException, so the caller still sees the checked type.

Java
static 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); // keeps the original as the cause
}
})
.toList();
} catch (UncheckedIOException e) {
throw e.getCause(); // the original IOException
}
}
Step throughHow the IOException reaches the caller
  1. Files.readString throws IOExceptioninside the lambda
  2. Lambda wraps itnew UncheckedIOException(e)
  3. Stream stops and rethrowsunchecked exceptions pass through map and toList
  4. readAll catches UncheckedIOExceptionat the method boundary
  5. readAll throws e.getCause()the caller sees IOException again

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

Notice the two halves. Wrapping lets the exception leave the lambda, and unwrapping restores the method's contract, so callers are forced by the compiler to handle IOException. getCause() of an UncheckedIOException is declared to return IOException, so the throw compiles without a cast. The cost is noise inside the lambda, which the next option removes.

4Option 3: A ThrowingFunction Interface and a Helper

If the pattern appears in many places, we move the wrapping into a small reusable piece. We declare our own functional interface whose method is allowed to throw IOException, and a helper that turns it into a normal Function.

Java
@FunctionalInterface
interface IoFunction<T, R> {
R apply(T t) throws IOException;
}
static <T, R> Function<T, R> unchecked(IoFunction<T, R> f) {
return t -> {
try { return f.apply(t); }
catch (IOException e) { throw new UncheckedIOException(e); }
};
}
static List<String> readAll(List<Path> paths) throws IOException {
try {
return paths.stream().map(unchecked(Files::readString)).toList();
} catch (UncheckedIOException e) {
throw e.getCause();
}
}

Now the pipeline reads almost like the original line, and Files::readString fits IoFunction because the interface method declares the same exception. The helper still wraps, so the unwrap at the boundary is still needed. Many teams keep exactly one such helper in a shared module rather than writing a new one in every class.

5What Not to Do

Two shortcuts compile but break the requirement. The first catches the exception and prints it or logs it, then returns null or an empty string. The pipeline carries on, the caller gets a list with holes in it, and the real failure is visible only in a log that nobody reads. The second catches and ignores. Both turn a loud, specific failure into a quiet wrong result.

A third trick, often called sneaky throw, uses a generic cast to rethrow the checked exception without declaring it. It compiles and keeps the original type, but the compiler no longer knows the exception can happen, so callers are never told to handle it. For this question, where the IOException must stay visible to the caller, it defeats the purpose.

6Which One to Choose

For a single method that mostly does I/O, I would use the loop: shortest, clearest, and the compiler does the rest. For codebases that use streams heavily with I/O, I would use the shared helper from option 3 with an unwrap at the method boundary. Option 2 written by hand is fine once, but repeated in many places it becomes noise.

7Follow-up questions

Does wrapping change the behaviour of the stream?

Yes, in a useful way: the first failing file throws, the stream stops processing further elements and the exception propagates out of toList(). That is the same fail-fast behaviour as the loop. If we wanted to read every file and collect all failures, we would need a different design, such as collecting results and errors separately.

Why not catch Exception in the helper instead of IOException?

Because that would also wrap unchecked exceptions and InterruptedException, hiding bugs and losing the interrupt status. A helper should catch exactly the checked exception it is meant to convert.

Can a parallel stream throw the wrapped exception differently?

In a parallel stream the exception is thrown from a worker thread and rethrown to the caller by the framework, still as an UncheckedIOException, so the same unwrap works. Other files may already have been read by other threads, though, so the operation is not stopped as neatly.

8Conclusion

In this answer, we saw that the code does not compile because Function.apply cannot throw checked exceptions, so Files.readString cannot be called directly in map. We wrote three correct versions that keep IOException visible: a plain loop with throws IOException, wrapping in UncheckedIOException inside the lambda and unwrapping at the method boundary, and a reusable IoFunction interface with a helper. We also saw why swallowing the exception, returning null or sneaky throws are wrong here.

What to say in the interviewAbout 90 seconds aloud

Open with

The code doesn't compile because map takes a Function, and Function's apply method doesn't declare any checked exceptions, so the lambda can't throw the IOException from Files.readString. Declaring throws on my method doesn't help, because the exception would leave apply, not my method.

Then, if they want more

If the caller must see the IOException, my first choice is a plain for loop in a method that declares throws IOException; for I/O-heavy code that's the clearest version and the compiler enforces handling at every caller.

If I want to keep the stream, I catch IOException inside the lambda and rethrow it as UncheckedIOException, which the JDK provides for exactly this, and then at my method boundary I catch UncheckedIOException and throw its getCause, which is typed as IOException, so the method contract stays checked.

If this pattern appears a lot, I define a small IoFunction interface whose apply throws IOException, plus a helper that converts it into a normal Function by doing the wrapping, so the pipeline reads as map of unchecked of Files::readString.

What I would never do is catch and log, return null or an empty string, because that hides the failure and gives the caller a list with holes. I'd also avoid sneaky throws here, since it hides the exception from the compiler and the requirement is to keep it visible.

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 "Make this compile and keep the IOException visible to the caller:": https://scrivio-interview-library.netlify.app/java/lambdas/10d9b3e213/