Video in progress

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

The standard functional interfaces (Function, Consumer) don't declare checked exceptions, so you have to catch it inside the lambda and wrap it in an unchecked one. Options: try/catch with UncheckedIOException, a helper wrapper method, or your own functional interface.

📖 Answer

The problem:

List<String> contents = paths.stream()
        .map(Files::readString)   // compile error: unhandled IOException
        .toList();

The most direct way is to wrap it in place:

.map(p -> {
    try {
        return Files.readString(p);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
})

If you need it in many places, you write a wrapper once:

@FunctionalInterface
interface ThrowingFunction<T, R> {
    R apply(T t) throws Exception;

    static <T, R> Function<T, R> unchecked(ThrowingFunction<T, R> f) {
        return t -> {
            try {
                return f.apply(t);
            } catch (RuntimeException e) {
                throw e;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        };
    }
}

paths.stream().map(ThrowingFunction.unchecked(Files::readString)).toList();

One important question remains: what should you do with the error? If one file can't be read, should the whole process stop, or should just that file be skipped? In the second case don't throw an exception: wrap the result in an Optional or your own Result record and collect the errors separately afterward.

You'll also come across the "sneaky throw" trick: throwing a checked exception through a generic without declaring it. It works, but the calling code doesn't expect it and can't write catch (IOException e). In library code I'm against it.