[英]Java 8 Optional How to define Error Message of NullPointerException
Before Java 8, we normally have to do like the following to fail fast for Null
values. 在Java 8之前,我们通常必须执行以下操作才能快速为
Null
值失败。
Objects.requireNonNull(pointer, "Your Error Message");
According to Java 8 Documentation, Optional.of
will throw NullPointerException
if passed parameter is null. 根据Java 8 Documentation,如果传递的参数为null,
Optional.of
将抛出NullPointerException
。
// Optional.of - throws NullPointerException if passed parameter is null
Optional<Integer> b = Optional.of(value2);
Is there any way to define error message for NullPointerException
in Java 8 Optional
? 有没有办法在Java 8中为
NullPointerException
定义错误消息 Optional
?
你总是可以编写Optional.of(Objects.requireNonNull(pointer, "message"))
。
For the Optional
class, you're usually expected to not deal with throwing any errors until the value is extracted. 对于
Optional
类,通常期望在提取值之前不处理任何错误。 You can use orElseThrow
when you try to retrieve the value: 您尝试检索值时可以使用
orElseThrow
:
Optional.ofNullable(pointer)
...
...
.orElseThrow(() -> new NullPointerException("message"));
The Optional
class isn't meant to replace the existing methods for doing specific null-checking. Optional
类不是要替换现有的进行特定null检查的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.