How do I throw exceptions if Optional is empty using orElseThrow?

In Java, you can throw exceptions when an Optional is empty using the orElseThrow method. This method accepts a Supplier that provides the exception to be thrown if the Optional is empty.

Here’s the syntax and an example:

package org.kodejava.util;

import java.util.Optional;

public class Main {
   public static void main(String[] args) {
      Optional<String> optionalValue = Optional.empty();

      // Throws an exception if Optional is empty
      String value = optionalValue.orElseThrow(() -> new IllegalArgumentException("Value is not present"));

      System.out.println(value);
   }
}

Explanation:

  1. orElseThrow():
    • This method is used to retrieve the value from an Optional.
    • If the Optional is empty (Optional.empty()), it throws the exception provided by the Supplier.
  2. Key Points:
    • orElseThrow takes a lambda expression or method reference as its argument. This lambda (or Supplier) returns the exception to be thrown.
    • Example of a custom exception:
    Optional<String> optionalValue = Optional.empty();
    
    String value = optionalValue.orElseThrow(() -> new MyCustomException("Custom message"));
    
  3. Method Reference Example:
    If the exception has a default constructor, you can use a method reference:

    Optional<String> optionalValue = Optional.empty();
    
    String value = optionalValue.orElseThrow(MyCustomException::new);
    
  4. When Optional is not empty:
    If the Optional contains a value (i.e., Optional.of("value")), the value is retrieved instead of throwing an exception.

    Optional<String> optionalValue = Optional.of("Hello");
    
    String value = optionalValue.orElseThrow(() -> new IllegalArgumentException("Value is not present"));
    
    System.out.println(value); // Prints "Hello"
    

Custom Exception Example:

If you want to define your own custom exception:

class MyCustomException extends RuntimeException {
    public MyCustomException(String message) {
        super(message);
    }
}

And use it with orElseThrow:

Optional<String> optionalValue = Optional.empty();

String value = optionalValue.orElseThrow(() -> new MyCustomException("Custom exception message"));

Using orElseThrow is a clean and concise way to handle empty Optional values by throwing appropriate exceptions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.