Video in progress

Strong Middle ☕ Core Java

How do you call a method that throws a checked exception inside a stream or a lambda?

Standard interfaces like Function and Consumer have no checked exceptions. You either wrap it in an unchecked exception inside the lambda, write your own functional interface, or return the error as a result.

📖 Answer

The problem:

paths.stream()
     .map(p -> Files.readString(p))   // compile error: IOException
     .toList();
  1. Wrapping in an unchecked exception is the most common:
.map(p -> {
    try { return Files.readString(p); }
    catch (IOException e) { throw new UncheckedIOException(e); }
})

The JDK has UncheckedIOException for exactly this purpose. For other types, use your own runtime exception.

  1. A helper wrapper:
@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); }
    };
}

paths.stream().map(unchecked(Files::readString)).toList();
  1. Turning the error into data: when a failure on one file shouldn't stop the whole job:
sealed interface Read permits Ok, Failed {}
record Ok(Path p, String text) implements Read {}
record Failed(Path p, IOException e) implements Read {}

There's also the "sneaky throw" trick (hiding a checked exception from the compiler through a generic), but it deceives the caller: the method signature has no IOException, and you can't write catch (IOException e). Avoid it in library code.

Also: in a parallel stream, the exception is passed to the caller no matter which thread it occurred on, but the remaining elements may keep being processed.