Java Language Optional Throw an exception, if there is no value


Use the orElseThrow() method of Optional to get the contained value or throw an exception, if it hasn't been set. This is similar to calling get(), except that it allows for arbitrary exception types. The method takes a supplier that must return the exception to be thrown.

In the first example, the method simply returns the contained value:

Optional optional = Optional.of("something");

return optional.orElseThrow(IllegalArgumentException::new);
// returns "something" string

In the second example, the method throws an exception because a value hasn't been set:

Optional optional = Optional.empty();

return optional.orElseThrow(IllegalArgumentException::new);
// throws IllegalArgumentException

You can also use the lambda syntax if throwing an exception with message is needed:

optional.orElseThrow(() -> new IllegalArgumentException("Illegal"));