Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Introduction

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

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

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.

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.

3. In Action

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.

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

We can verify the behavior by running this test:

public void whenIdIsNull_thenExceptionIsThrown() {
    assertThrows(InvalidArgumentException.class, () -> Optional

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

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

public void whenIdIsNonNull_thenNoExceptionIsThrown() {
    assertAll(() -> Optional

4. Conclusion

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

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

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Generic footer banner
Comments are closed on this article!