Sometimes, if Optional is empty, we want to throw an exception (for example, NoSuchElementException). The clumsy solution to this problem is listed as follows:
// Avoid
public String findStatus() {
Optional<String> status = ...; // this is prone to be empty
if (status.isPresent()) {
return status.get();
} else {
throw new NoSuchElementException("Status cannot be found");
}
}
But a much more elegant solution will rely on the Optional.orElseThrow() method. The signature of this method, orElseThrow(Supplier<? extends X> exceptionSupplier), allows us to give the exception as follows (if the value is present then orElseThrow() will return it):
// Prefer
public String findStatus() {
Optional<String> status = ...; // this is prone to be empty
return status.orElseThrow(
() -> new NoSuchElementException("Status cannot be found"));
}
Or, another exception is, for example, IllegalStateException:
// Prefer
public String findStatus() {
Optional<String> status = ...; // this is prone to be empty
return status.orElseThrow(
() -> new IllegalStateException("Status cannot be found"));
}
Starting with JDK 10, Optional was enriched with an orElseThrow() flavor without arguments. This method implicitly throws NoSuchElementException:
// Prefer (JDK 10+)
public String findStatus() {
Optional<String> status = ...; // this is prone to be empty
return status.orElseThrow();
}
Nevertheless, be aware that throwing an unchecked exception without a meaningful message in production is not good practice.