Issue
Checked exceptions wrapped to throw Runtime exception in streams is failing with compilation error in JDK 11 and 12.
package com.mmk.test;
import java.net.URL;
import java.util.ArrayList;
import java.util.function.Function;
public class App {
public static void main(String[] args) {
var list = new ArrayList<String>();
list.add("http://foo.com");
list.stream().map(wrap(url -> new URL(url)));
}
static <T, R, E extends Throwable> Function<T, R>
wrap(FunException<T, R, E> fn) {
return t -> {
try {
return fn.apply(t);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
};
}
interface FunException<T, R, E extends Throwable> {
R apply(T t);
}
}
Expected: No compilation error and no output. Actual: Compilation error, Unhandled Exception.
Solution
The FunException::apply
method does not declare any exceptions to be thrown, so when you create a lambda that can throw an exception
url -> new URL(url)
The compiler complains because you are not handling this exception, and FunException::apply
does not declare it in it's throws
clause either.
You can make it work by adding a throws
clause, i.e.:
interface FunException<T, R, E extends Throwable> {
R apply(T t) throws E;
}
Answered By - Jorn Vernee
Answer Checked By - Senaida (JavaFixing Volunteer)