You can do some improvements to the answer that @Tobias has provided.
In the question, I can see you want to pass some input of generic type (let assume T) and expect and Optional<R> type.
This is new functional interface look like,
@FunctionalInterface
public interface FunctionException<T, R> {
public R apply(T t) throws Exception;
}
Then new expectation wrapper,
public <T,R> Optional<R> wrapException(Function<T, R> function, T t) {
try { return Optional.of(function.apply(t)); }
catch (Exception e) {
System.out.println(e.getLocalizedMessage());
// todo: add logger
}
return Optional.empty();
};
You can pass any method that have following signature to wrapException method.
R yourMethod(T t) throws Exception
Here is an example,
public boolean someMethod(int in) throws IOException {
// your business logic
// my business logic
if (in == 4) throw new IOException("Some exception");
return in == 3;
};
You can call wrapException like this
Optional<Boolean> a = wrapException(YourClass::someMethod, 2);
Optional<Boolean> b = wrapException(YourClass::someMethod, 4);