我最近发现自己写了许多以下形式的块:
try {
return Optional.of(thing.doSomething(arg));
} catch (Exception e) {
System.out.println(e.getMessage());
return Optional.empty();
}
Run Code Online (Sandbox Code Playgroud)
这是必要的,因为某些方法表示它们可能会引发异常,并且如果我不将这些方法包含在try / catch块中,则Eclipse会对我大吼大叫。
所以我这样写:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
因此,我传递给tryOpt的任何函数都包含在try / catch块中并安全地执行,并且其结果作为Optional返回。但是Eclipse仍然对我大吼大叫:
return tryOpt(
((x) -> thing.doSomething(x)),
arg);
Run Code Online (Sandbox Code Playgroud)
我的问题是,有没有什么办法,我告诉Eclipse和/或Java编译器,它的好,那我我间接地包围的try / catch块中的违规方法?还是我只是误解了Java的工作原理,在这种情况下,有人会启发我吗?或者,另一方面,在这种情况下,我可以安全地忽略Eclipse的红线警告吗?