ido*_*lax 0 java functional-programming java-8
当为可空的可选抛出异常时,我收到编译错误,要求我捕获或声明异常为抛出,但 NPE 是不需要捕获的运行时异常。所以基本上 orElseThrow 行为与在 java 8 之前抛出异常不同。这是一个特性还是一个错误?有什么想法吗?
这不编译:
protected String sendTemplate() {
String template = getTemplate();
return Optional.ofNullable(template).orElseThrow(() -> {
throw new NullPointerException("message");
});
}
Run Code Online (Sandbox Code Playgroud)
这样做:
protected String sendTemplate() {
String template = getTemplate();
if (template == null){
throw new NullPointerException("message");
}
else return template;
}
Run Code Online (Sandbox Code Playgroud)
该Supplier传给orElseThrow应该返回所构建的例外,这是有关该方法,其中声明扔供应商返回什么的一般签名。由于您的供应商不返回值,JDK 8javac推断Throwable并要求调用者orElseThrow处理它。较新的编译器RuntimeException在这种情况下可以方便地进行推断并且不会产生错误。
不过,正确的用法是
protected String sendTemplate1() {
String template = getTemplate();
return Optional.ofNullable(template)
.orElseThrow(() -> new NullPointerException("message"));
}
Run Code Online (Sandbox Code Playgroud)
但Optional无论如何,这是一种过度使用。你应该简单地使用
protected String sendTemplate() {
return Objects.requireNonNull(getTemplate(), "message");
}
Run Code Online (Sandbox Code Playgroud)
见requireNonNull(T, String)和requireNonNull(T, Supplier<String>)。