orElseThrowWith<X extends Object> method
T
orElseThrowWith<X extends Object>([
- X exceptionSupplier()?
If a value is present, returns the value, otherwise throws an exception produced by the exception supplying function.
API Note
A function reference to an exception constructor can be used as the supplier.
For example, () => InvalidArgumentException('Custom message')
exceptionSupplier
the supplying function that produces an exception to be thrown
Returns the value, if present.
Throws the exception produced by exceptionSupplier
if no value is present.
Throws InvalidArgumentException if no value is present and the exception supplying function is null.
Example
Optional<String> name = Optional.of("Mia");
Optional<String> empty = Optional.empty();
// With present value
print(name.orElseThrow(() => InvalidArgumentException("Name required"))); // "Mia"
// With empty optional
try {
print(empty.orElseThrow(() => InvalidArgumentException("Name is required")));
} catch (e) {
print("Error: $e"); // Error: Invalid argument(s): Name is required
}
// Different exception types
try {
empty.orElseThrow(() => InvalidFormatException("Invalid format"));
} catch (e) {
print("Format error: $e");
}
// Custom exceptions
class UserNotFoundException extends RuntimeException {
final String message;
UserNotFoundException(this.message);
@override
String toString() => "UserNotFoundException: $message";
}
Optional<String> userId = Optional.empty();
try {
String id = userId.orElseThrow(() => UserNotFoundException("User not found"));
} catch (e) {
print("Custom error: $e");
}
// In validation scenarios
String validateAndGetEmail(Optional<String> email) {
return email
.filter((e) => e.contains('@'))
.orElseThrow(() => InvalidArgumentException('Invalid email format'));
}
Implementation
T orElseThrowWith<X extends Object>([X Function()? exceptionSupplier]) {
if (exceptionSupplier == null) {
throw InvalidArgumentException('exceptionSupplier cannot be null');
}
if (_value != null) {
return _value as T;
} else {
throw exceptionSupplier();
}
}