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

JavaJava 8Java Stream

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

Sure.

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

Solution 2 - Java

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.

Solution 3 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmdoView Question on Stackoverflow
Solution 1 - JavaLouis WassermanView Answer on Stackoverflow
Solution 2 - JavaManuView Answer on Stackoverflow
Solution 3 - JavaAshish PushpView Answer on Stackoverflow