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:
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 theSupplier
.
- This method is used to retrieve the value from an
- Key Points:
orElseThrow
takes a lambda expression or method reference as its argument. This lambda (orSupplier
) returns the exception to be thrown.- Example of a custom exception:
Optional<String> optionalValue = Optional.empty(); String value = optionalValue.orElseThrow(() -> new MyCustomException("Custom message"));
- 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);
- When
Optional
is not empty:
If theOptional
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.