当为可空可选抛出异常时,我收到编译错误,要求我捕获或声明抛出的异常,但 NPE 是不需要捕获的运行时异常。所以基本上 orElseThrow 行为与 java 8 之前的抛出异常不同。 这是一个功能还是一个错误?有什么想法吗?
这不能编译:
protected String sendTemplate() {
String template = getTemplate();
return Optional.ofNullable(template).orElseThrow(() -> {
throw new NullPointerException("message");
});
}
这样做是:
protected String sendTemplate() {
String template = getTemplate();
if (template == null){
throw new NullPointerException("message");
}
else return template;
}
最佳答案
Supplier
传递至orElseThrow
应该返回构造的异常,这与该方法的通用签名相关,该方法声明抛出供应商返回的内容。由于您的供应商不返回值,因此 JDK 8 javac
推断Throwable
并要求调用者 orElseThrow
来处理它。较新的编译器可以方便地推断 RuntimeException
在这种情况下并且不会产生错误。
不过,正确的用法是
protected String sendTemplate1() {
String template = getTemplate();
return Optional.ofNullable(template)
.orElseThrow(() -> new NullPointerException("message"));
}
但是这是对 Optional
的过度使用反正。您应该简单地使用
protected String sendTemplate() {
return Objects.requireNonNull(getTemplate(), "message");
}
参见 requireNonNull(T, String)
和 requireNonNull(T, Supplier<String>)
.
关于java - 可选的 throw 需要 NPE 的 throws 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57053594/