Optional orElseThrow Method

In this tutorial, we will demonstrate how to throw an exception if the value is not present in the Optional object using orElseThrow() method.

The orElseThrow() method returns the contained value, if present, otherwise throws an exception to be created by the provided supplier.

Optional orElseThrow() Method Example

In the below example, we pass a null value to the Optional object so orElseThrow() method throws an exception to be created by the provided supplier.

package com.java.lambda.optional;

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = null;
        Optional<String> stringOptional = Optional.ofNullable(email);
        String optionalObject = stringOptional.orElseThrow(() -> new IllegalArgumentException("Email is not exist"));
        System.out.println(optionalObject);
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Email is not exist
	at com.java.lambda.optional.OptionalDemo.lambda$main$0(OptionalDemo.java:10)
	at java.base/java.util.Optional.orElseThrow(Optional.java:403)
	at com.java.lambda.optional.OptionalDemo.main(OptionalDemo.java:10)
In the below example, we pass a non-null value to the Optional object so orElseThrow() method returns a value from the Optional object:
import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = "ramesh@gmail.com";
        Optional<String> stringOptional = Optional.ofNullable(email);
        String optionalObject = stringOptional.orElseThrow(() -> new IllegalArgumentException("Email is not exist"));
        System.out.println(optionalObject);
    }
}

Output:

ramesh@gmail.com

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments