mdo
mdo

Reputation: 7111

Java 8 method references: provide a Supplier capable of supplying a parameterized result

I'd like to use

java.util.Optional.orElseThrow()

with an Exception type that asks for a constructor parameter. Something like this:

.orElseThrow(MyException::new(someArgument)) // obviously NOT working

Is there a way to create a Supplier that passes my argument value in?

Upvotes: 311

Views: 144031

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198103

Sure.

.orElseThrow(() -> new MyException(someArgument))

Upvotes: 611

Manu
Manu

Reputation: 3635

It appears that you can throw only RuntimeException from the method orElseThrow. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException

Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.

Upvotes: 26

Ashish Pushp
Ashish Pushp

Reputation: 238

optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));

Upvotes: 13

Related Questions