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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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"));


Got any Java Language Question?