Throw Exception in Optional in Java 8 – 在Java 8中用可选方式抛出异常

最后修改: 2018年 8月 29日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this tutorial, we’re going to show how to throw a custom exception when an Optional is empty.

在本教程中,我们将展示如何在Optional is空时抛出一个自定义异常。

If you want to go deeper into Optional, take a look at our full guide, here.

如果你想更深入地了解可选性,看看我们完整的指南,这里。

2. Optional.orElseThrow

2.Optional.orElseThrow

Simply put, if the value is present, then isPresent() would return true, and calling get() will return this value. Otherwise, it throws NoSuchElementException.

简单地说,如果该值是存在的,那么isPresent()将返回true,并且调用get()将返回这个值。否则,它会抛出NoSuchElementException

There’s also a method orElseThrow(Supplier<? extends X> exceptionSupplier) that allows us to provide a custom Exception instance. This method will return value only if it’s present. Otherwise, it’ll throw an exception created by a provided supplier.

还有一个方法orElseThrow(Supplier<? extends X> exceptionSupplier),它允许我们提供一个自定义的异常实例。这个方法只有在它存在的情况下才会返回值。否则,它将抛出一个由提供的供应商创建的异常。

3. In Action

3.行动中

Imagine that we have a method which returns a nullable result:

想象一下,我们有一个方法,该方法返回的结果是空的:

public String findNameById(String id) {
    return id == null ? null : "example-name";
}

Now we’re going to call our findNameById(String id) method twice and wrap the result with an Optional by using the ofNullable(T value) method.

现在我们将调用我们的findNameById(String id)方法两次,并通过使用ofNullable(T value)方法将结果包装成一个Optional

Optional provides a static factory method for creating new instancesThis method is called ofNullable(T value). Then we can call orElseThrow.

Optional提供了一个静态工厂方法来创建新的实例这个方法叫做ofNullable(T value)。然后我们可以调用orElseThrow.

We can verify the behavior by running this test:

我们可以通过运行这个测试来验证这个行为。

@Test
public void whenIdIsNull_thenExceptionIsThrown() {
    assertThrows(InvalidArgumentException.class, () -> Optional
      .ofNullable(personRepository.findNameById(null))
      .orElseThrow(InvalidArgumentException::new));
}

According to our implementation, findNameById will return null. So the new InvalidArgumentException will be thrown from the orElseThrow method.

根据我们的实现,findNameById将返回null。所以新的InvalidArgumentException将从 orElseThrow方法中抛出。

We can call this method with a non-null argument. Then, we won’t get an InvalidArgumentException:

我们可以用一个非空的参数来调用这个方法。然后,我们就不会得到一个InvalidArgumentException:

@Test
public void whenIdIsNonNull_thenNoExceptionIsThrown() {
    assertAll(() -> Optional
      .ofNullable(personRepository.findNameById("id"))
      .orElseThrow(RuntimeException::new));
}

4. Conclusion

4.结论

In this quick article, we discussed how to throw an exception from Java 8 Optional. 

在这篇快速文章中,我们讨论了如何从Java 8 选择抛出一个异常。

As always, we put the source code on our GitHub.

像往常一样,我们把源代码放在我们的GitHub上