Issue
I've recently found myself writing many blocks of the following form:
try {
return Optional.of(thing.doSomething(arg));
} catch (Exception e) {
System.out.println(e.getMessage());
return Optional.empty();
}
This is necessary because certain methods signal that they may throw exceptions, and Eclipse yells at me if I don't surround those methods with try/catch blocks.
So I wrote this:
public static <A, T> Optional<T> tryOpt (Function<A, T> f, A arg) {
try {
return Optional.of(f.apply(arg));
} catch (Exception e) {
System.out.println(e.getMessage());
return Optional.empty();
}
}
So any Function I pass to tryOpt is enclosed in a try/catch block and safely executed, and its result returned as an Optional. But Eclipse still yells at me for using it:
return tryOpt(
((x) -> thing.doSomething(x)),
arg);
My question is, is there any way for me to tell Eclipse and/or the java compiler that it's okay, and that I am indirectly enclosing the offending method within a try/catch block? Or have I just misunderstood something about how java works, in which case, would someone mind enlightening me? Or, on the other hand, can I safely ignore Eclipse's red-line warnings in this case?
Solution
Function.apply
does not allow to throw an exception, therefore the compiler complains when you pass in a lambda expression which does that.
You can resolve this issue by using a functional interface which allows to throw exceptions. (Maybe such a interface already exists in one of the java.util.* packages):
public static <A, T> Optional<T> tryOpt (Fn<A, T> f, A arg) {
try {
return Optional.of(f.apply(arg));
} catch (Exception e) {
System.out.println(e.getMessage());
return Optional.empty();
}
}
public static interface Fn<A, T> {
T apply(A a) throws Exception;
}
Answered By - wero
Answer Checked By - David Goodson (JavaFixing Volunteer)