orElseThrow method
T
orElseThrow()
If a value is present, returns the value, otherwise throws InvalidArgumentException.
Returns the non-null value described by this Optional.
Throws InvalidArgumentException if no value is present.
Example
Optional<String> name = Optional.of("Liam");
Optional<String> empty = Optional.empty();
print(name.orElseThrow()); // "Liam"
try {
print(empty.orElseThrow());
} catch (e) {
print("Error: $e"); // Error: Bad state: No value present
}
// Preferred over get() method
String safeName = name.orElseThrow(); // Clear intent
Implementation
T orElseThrow() {
if (_value == null) {
throw InvalidArgumentException('No value present');
}
return _value as T;
}