java.util.Optional<T>
Optional<T>
is a generic class introduced in Java 8 to represent a value that may or may not be present, reducing the risk of NullPointerException
.
T
or no value (empty
).public T orElseThrow()
Returns the value if present; otherwise, throws NoSuchElementException
.
Example:
Optional<String> optional = Optional.ofNullable(null);
String value = optional.orElseThrow(); // Throws NoSuchElementException
public T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable
Returns the value if present; otherwise, throws an exception created by the Supplier
.
Example:
Optional<String> optional = Optional.ofNullable(null);
String value = optional.orElseThrow(() -> new IllegalArgumentException("Value not found!"));
Definition: A functional interface with a single abstract method (SAM): public T get()
.
Used to supply an object, such as a custom exception in orElseThrow
.
Example in a service layer:
public class RestaurantService {
private final RestaurantDao restaurantDao;
public RestaurantService(RestaurantDao restaurantDao) {
this.restaurantDao = restaurantDao;
}
public Restaurant findRestaurantById(Long restaurantId) {
return restaurantDao.findById(restaurantId)
.orElseThrow(() -> new MyCustomException("Restaurant not found !!!!!"));
}
}
public class UserService {
private final UserDao userDao;
public UserService(UserDao userDao) {
this.userDao = userDao;
}
public User findUserById(Long userId) {
return userDao.findById(userId).orElseThrow(() -> new ResourceNotFoundException("Invalid User Id"));
}
}
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
Spring Boot is a framework that simplifies Spring application development by providing auto-configuration, standalone applications, and production-ready features.