I am trying to wrap methods which throws checked exceptions.. I am following steps told in this url: https://www.rainerhahnekamp.com/en/ignoring-exceptions-in-java/
Interestingly when I write the code like this:
IntStream.range(1, locales.length)
.mapToObj(i -> locales[i].toString())
.forEach(wrap(this::testLocale));
it is working fine but when I write like this:
IntStream.range(1, locales.length)
.mapToObj(i -> locales[i].toString())
.forEach(s -> wrap(testLocale(s)));
Intellij is complaining "Unhandled Exception: java.lang.Exception"
here testLocale looks like this:
void testLocale(String s) throws Exception
The wrap function looks like this:
public static <T> Consumer<T> wrap(WrapConsumer<T> wrapper) {
return t -> {
try {
wrapper.accept(t);
} catch(Exception exception) {
throw new RuntimeException(exception);
}
};
}
and WrapConsumer is a function interface with Consumer signature:
@FunctionalInterface
public interface WrapConsumer<T> {
void accept(T t) throws Exception;
}
I am banging my head trying to understand why Intellij is complaining based on how I write the lambda
You are supposed to provide a wrapped consumer to forEach via:
.forEach(wrap(this::testLocale));
what you are doing via s -> wrap(testLocale(s)) is provide a new consumer that still can't handle the checked Exception.
Probably simpler to understand would be that forEach accepts a Consumer that has a method definition of:
void accept(T t); // does not define to throw the checked Exception
When you do forEach(s -> ...), it is this Consumer::accept that you are using.
On the other hand that forEach(wrap(this::testLocale)); will return a Consumer still, but by accepting as input a WrapConsumer<T> wrapper that does declare to throw that Exception via:
void accept(T t) throws Exception;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With