Member-only story
How do you handle checked exceptions in Stream Pipeline ?
Java streams don’t handle checked exceptions gracefully with lambda expressions , One approach could be is to wrap the code that throws a checked exception in a separate method and handle the exception there, either by converting it to an unchecked exception or by implementing a custom functional interface that can throw checked exceptions. You Need to follow below steps:
1. Define a Functional Interface.
2. Create a wrapper method that converts the checked exception in to unchecked and throws that.
3. Use that Wrapper method in your implementation.
Let’s Look at the code.
package com.handle.stream.checkedexception;
import java.util.function.Function;
@FunctionalInterface
public interface ExceptionInterface<T, R, E extends Exception> {
R apply(T t) throws E;
public static <T, R, E extends Exception> Function<T, R> unchecked(ExceptionInterface<T, R, E> function) {
return t -> {
try {
return function.apply(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
}
This code defines a functional interface called ExceptionInterface with a single abstract method apply(T t) that takes an input of type T and returns a result of type R, and may throw an exception of type E. This interface is annotated with @FunctionalInterface to indicate that it’s intended to be used as a functional…