All 15 Functional Interfaces & Method References questions
More in Functional Interfaces & Method References
Advertisement
Java › Functional Interfaces & Method References

How would you convert a checked-exception-throwing method into a lambda usable with a standard functional interface (which doesn't declare any checked exceptions), given standard interfaces like Function don't permit checked exceptions in their abstract method signature?

Intermediate

Answer

Since none of the standard java.util.function interfaces declare a checked exception in their functional method's signature, a lambda body that calls a method throwing a checked exception won't compile directly against one of these interfaces -- common workarounds include wrapping the checked exception in an unchecked one inside the lambda body (catching and rethrowing as a RuntimeException), or defining a custom functional interface whose method DOES declare the checked exception (usable in contexts where you control what accepts it), or using a utility 'sneaky throw' technique (an unusual, somewhat controversial approach exploiting generics type erasure to throw a checked exception without a throws declaration).
// Standard Function doesn't allow this to compile directly:
// Function<String, byte[]> reader = Files::readAllBytes;  // COMPILE ERROR: IOException is checked

// Workaround: wrap the checked exception as unchecked inside the lambda
Function<String, byte[]> reader = path -> {
    try {
        return Files.readAllBytes(Path.of(path));
    } catch (IOException e) {
        throw new UncheckedIOException(e);  // wraps checked as unchecked, now compiles fine
    }
};
Real-world example A stream pipeline processing a list of file paths and reading each file's contents wraps the checked IOException from Files.readAllBytes() in an UncheckedIOException inside the lambda body, allowing the method reference/lambda to satisfy the standard Function interface's unchecked-only signature while still preserving the original exception as the cause for downstream handling.

Common follow-ups: What is the 'sneaky throw' technique, and why is it considered controversial despite technically working?;How would defining your own checked-exception-permitting functional interface change this trade-off?