304

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?

simhumileco
  • 31,877
  • 16
  • 137
  • 115
mdo
  • 6,961
  • 3
  • 24
  • 26

3 Answers3

603

Sure.

.orElseThrow(() -> new MyException(someArgument))
simhumileco
  • 31,877
  • 16
  • 137
  • 115
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
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.

Manu
  • 3,467
  • 3
  • 29
  • 28
  • 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 '15 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 '17 at 15:15
  • **Incorrect** according to the class documentation for [`Optional.orElseThrow`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#orElseThrow-java.util.function.Supplier-) which says you can throw a [`Throwable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html) which means an `Error` or any `Exception`. – Basil Bourque Aug 23 '18 at 23:17
  • I think this was an issue with an older version of JDK 8. – Manu Dec 20 '18 at 07:35
  • @Manu Perhaps you are referring to [JDK-8047338](https://bugs.openjdk.java.net/browse/JDK-8047338) discussed on this Question, [*Throw RuntimeException inside Stream with Optional.orElseThrow*](https://stackoverflow.com/q/39076077/642706). 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. – Basil Bourque May 25 '19 at 17:08
13
optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));
Kartoch
  • 7,610
  • 9
  • 40
  • 68
Ashish Pushp
  • 228
  • 2
  • 9
  • i am getting error " The method orElseThrow(Supplier extends X>) in the type Optional is not applicable for the arguments (() -> {}) " – BdEngineer Jun 11 '19 at 07:16