307

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?

2
  • 48
    Why can't you do orElseThrow(() -> new MyException(someArgument))? Apr 7, 2014 at 15:51
  • 10
    Professional Java programmer with plenty of streams & Optional experience…I still end up here sometimes. And this is why I prefer Kotlin. Jun 22, 2018 at 19:54

3 Answers 3

608

Sure.

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

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.

5
  • 1
    thanks, this was throwing me off when using Optional in groovy. Trying to throw Exception from a groovy closure, but it failed with java.lang.reflect.UndeclaredThrowableException, changing to a RuntimeException fixed it.
    – Ted Naleid
    Apr 12, 2015 at 17:19
  • Good to know about that. Fortunately in my case, I'm using RuntimeExceptions, but this may not always be the case.
    – hbobenicio
    Jul 25, 2017 at 15:15
  • Incorrect according to the class documentation for Optional.orElseThrow which says you can throw a Throwable which means an Error or any Exception. Aug 23, 2018 at 23:17
  • I think this was an issue with an older version of JDK 8.
    – Manu
    Dec 20, 2018 at 7:35
  • @Manu Perhaps you are referring to JDK-8047338 discussed on this Question, Throw RuntimeException inside Stream with Optional.orElseThrow. If so, include in your Answer. I've not had quite enough coffee to discern if this is spot-on or not, so I'll refrain from editing your Answer myself. May 25, 2019 at 17:08
13
optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));
1
  • i am getting error " The method orElseThrow(Supplier<? extends X>) in the type Optional<QueryEntities> is not applicable for the arguments (() -> {}) "
    – BdEngineer
    Jun 11, 2019 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.