Daniel Pinyol
Daniel Pinyol

Reputation: 2262

How to throw when stream of javaslang Try contains an exception

In javaslang, if I have a Stream<Try<MyClass>, how can I throw when any of the items on the stream contains a checked Exception? I cannot do this because peek does not accept a throwing lambda

stream.peek(t -> t.onFailure((t2) -> {throw t2.getCause();}));

thanks

Upvotes: 0

Views: 652

Answers (2)

Daniel Dietrich
Daniel Dietrich

Reputation: 2272

Disclaimer: I'm creator of Javaslang

Because a Try wraps a checked exception in an unchecked NonFatalException, it is sufficient to call

  stream.peek(Try::get)

This will do nothing else but throwing the NonFatalException(<original-exception>) when a Failure comes along.


Please note that we will change the behaviour slightly in Javaslang 3.0. Try will not wrap exceptions any more. Instead it will 'sneaky throw' the original exception. This is possible in Java with a little trick.

However, it will take some time until Javaslang 3.0 is released. Currently we work on 2.1.0.

Upvotes: 1

Sym-Sym
Sym-Sym

Reputation: 3606

Wrap the checked exception in RuntimeException.

throw new RuntimeException(checkedException);

Upvotes: 0

Related Questions