Learnitweb

Optional.orElseThrow()

1. Introduction

A container object which may or may not contain a non-null value. If a value is present, isPresent() returns true. If no value is present, the object is considered empty and isPresent() returns false.

Optional has a method get() which return a value if the value is present, otherwise throws NoSuchElementException.

The common way of using Option is like:

Optional<String> opt = Optional.of("test");
if(opt.isPresent()){
    System.out.println(opt.get());
}

The Optional.get() was kind of a naming mistake in Java 8. The naming convention is such that people often call Optional.get() without calling isPresent(). Optional.get() is the code smell. Optional.get() is often combined with Optional.isPresent(). This defeats the purpose of Optional. Optional.orElseThrow() is a transparently named synonym for the current behavior of get().

There are two versions of orElseThrow():

  • T orElseThrow()
    If a value is present, returns the value, otherwise throws NoSuchElementException.
  • T orElseThrow​(Supplier exceptionSupplier)
    If a value is present, returns the value, otherwise throws an exception produced by the exception supplying function.

2. Example

In the following example, there are 2 Optionals, one is with a value whereas another one is empty. When there is a value, orElseThrow() returns a value. When Optional is empty, orElseThrow throws NoSuchElementException.

public class OptionalExample {

    public static void main(String args[]) {
        // create a Optional
        Optional<Integer> op = Optional.of(99);

        System.out.println("When Optional is not empty: " + op.orElseThrow());

        //create an empty optional
        Optional<Integer> op2 = Optional.empty();

        System.out.println("When Optional is not empty: " + op2.orElseThrow());

    }
}

Output

When Optional is not empty: 99
Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.base/java.util.Optional.orElseThrow(Optional.java:377)

3. Conclusion

In summary, becoming proficient with the Optional.orElseThrow() method can significantly improve the robustness and clarity of your Java code, especially when handling potential null values. By utilizing this method, you can elegantly address scenarios where the absence of a value is exceptional and requires explicit handling. Remember that orElseThrow() allows you to gracefully navigate nullable situations by either safely retrieving the value or throwing a specified exception when necessary. Incorporating this technique into your coding practices will not only streamline your development process but also enhance the overall readability and reliability of your Java applications.