The orElseThrow() method in Java is a part of the java.util.Optional class, and its primary purpose is to retrieve the value contained within an Optional instance or, if no value is present, to throw an exception.
There are two main variations of
orElseThrow():- This version returns the value if it's present in the
Optional. - If the
Optionalis empty, it throws aNoSuchElementException.
- This version returns the value if it's present in the
- This version also returns the value if present.
- If the
Optionalis empty, it uses the providedexceptionSupplierto create and throw a custom exception of typeX. This allows for more specific error handling than the defaultNoSuchElementException.
How it works:
- If the
Optionalobject contains a non-null value,orElseThrow()simply returns that value. - If the
Optionalobject is empty (i.e., it doesn't contain a value),orElseThrow()will either throw aNoSuchElementException(in the no-argument version) or throw the exception generated by theexceptionSupplier(in the version with aSupplierargument).
Example:
0 Comments