orElseThrow() in Java

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():
  • public T orElseThrow():
    • This version returns the value if it's present in the Optional.
    • If the Optional is empty, it throws a NoSuchElementException.
  • public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X: 
    • This version also returns the value if present.
    • If the Optional is empty, it uses the provided exceptionSupplier to create and throw a custom exception of type X. This allows for more specific error handling than the default NoSuchElementException.
How it works:
  • Value Present: 
    If the Optional object contains a non-null value, orElseThrow() simply returns that value.
  • Value Not Present: 
    If the Optional object is empty (i.e., it doesn't contain a value), orElseThrow() will either throw a NoSuchElementException (in the no-argument version) or throw the exception generated by the exceptionSupplier (in the version with a Supplier argument).
Example:
Java
import java.util.Optional;import java.util.NoSuchElementException;public class OptionalOrElseThrowExample {    public static void main(String[] args) {        Optional<String> presentOptional = Optional.of("Hello");        Optional<String> emptyOptional = Optional.empty();        // Using orElseThrow() with a present value        String value1 = presentOptional.orElseThrow();        System.out.println("Value from present Optional: " + value1);        // Using orElseThrow() with a custom exception supplier        try {            String value2 = emptyOptional.orElseThrow(() -> new IllegalArgumentException("No value found in optional!"));            System.out.println("This won't be printed.");        } catch (IllegalArgumentException e) {            System.out.println("Caught custom exception: " + e.getMessage());        }        // Using orElseThrow() on an empty Optional (throws NoSuchElementException)        try {            String value3 = emptyOptional.orElseThrow();            System.out.println("This also won't be printed.");        } catch (NoSuchElementException e) {            System.out.println("Caught default exception: " + e.getMessage());        }    }}

Post a Comment

0 Comments