Course contentsShow
← Java
Lesson 1790 of 2,87037. Optional for Null SafetyFree lesson

Common Pitfalls with orElse Family Methods

Identify common mistakes like using orElse with method calls, returning null from orElseGet, and exception handling errors.

Common Pitfalls with orElse Family Methods

You'll learn the most frequent mistakes developers make when using orElse, orElseGet, and orElseThrow, and how to avoid them.

The Core Problem

Even experienced developers stumble with Optional's orElse family methods. These pitfalls often hide bugs, create performance issues, or compromise the safety that Optional is designed to provide.

Common Mistake #1: Using orElse with Method Calls

The biggest trap is passing a method call directly to orElse():

String result = optional.orElse(expensiveDefaultValue());

The problem: expensiveDefaultValue() executes every single time, even when the Optional contains a value. You've forgotten that orElse evaluates its argument immediately. Use orElseGet() instead:

String result = optional.orElseGet(() -> expensiveDefaultValue());

Common Mistake #2: Returning null from orElseGet

This defeats Optional's entire purpose:

String result = optional.orElseGet(() -> null); // DON'T DO THIS!

If you're providing null as the default, you're reintroducing the problem Optional was meant to solve. You've just delayed the NullPointerException instead of preventing it.

Common Mistake #3: Throwing Without Context

Using orElseThrow() without providing meaningful information:

String value = optional.orElseThrow(); // Vague NoSuchElementException

Better to supply a custom exception with context:

String value = optional.orElseThrow(() -> 
    new IllegalStateException("User configuration missing"));

Common Mistake #4: Misunderstanding Exception Handling

Thinking the Supplier in orElseThrow catches exceptions from the Optional creation—it doesn't. The Supplier only executes if the Optional is empty.

Key Takeaway: Avoid passing method calls to orElse(), never return null from orElseGet(), always provide contextual exceptions to orElseThrow(), and remember that Suppliers only execute on absence, not on upstream errors.