orElseThrow with Custom Exception Supplier
What you'll learn: How to provide custom exception suppliers to orElseThrow() for meaningful, domain-specific error messages.
The Problem with Generic Exceptions
You've already learned that orElseThrow() throws NoSuchElementException when an Optional is empty. But what if you need to throw a more specific exception that communicates why the value is missing in your business context?
Custom Exception Suppliers
The orElseThrow() method has an overloaded version that accepts a Supplier<? extends Throwable>. This lets you provide exactly the exception you want to throw, with context-specific messages that help debugging and error handling.
How It Works
Think of it like a vending machine with a custom alarm. Instead of a generic beep when your item is missing, it could announce "Chips out of stock—please try aisle 3." That's what a custom exception supplier does: it gives specific, actionable information.
Optional<User> userOpt = findUserById(123);
User user = userOpt.orElseThrow(() ->
new UserNotFoundException("User with ID 123 not found"));
The lambda () -> new UserNotFoundException(...) is a Supplier<UserNotFoundException>. It's only executed if the Optional is empty—making it lazy like orElseGet().
Why This Matters
Custom exception suppliers make your error handling domain-aware. Instead of catching generic NoSuchElementException everywhere, you catch meaningful exceptions like UserNotFoundException, OrderNotFoundException, or ConfigurationMissingException. This improves code clarity and makes debugging far easier.
Key Takeaway:
Use orElseThrow() with a custom exception supplier to throw domain-specific exceptions with meaningful messages, making your error handling clearer and more maintainable.