Optional orElseThrow Method

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

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

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare