Throw Exception in Optional in Java 8

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:

@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.

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

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

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.

Leave a Reply

Your email address will not be published.