I have defined this stream:
public int sumNumbers(int[] numbers) {
return IntStream.of(numbers)
.filter(n -> n <= 1000)
.sum();
}
Where I'm summing all integers that are not higher than 1000. But now what I want to do is, throw an exception if any element of the array is negative.
I know how to do it in the old fashioned mode, but I was wondering if there's any mechanism with Stream
and .filter()
where I can define a filter and an exception case for that filter
Just to clarify I want to throw an exception, and not control a runtime exception as the other question does.
The idea here is that if my filter is true in:
filter(n -> n < 0 throw Exception)
Unfortunately, we cannot do it in a Java stream because the map method accepts only a Function.
You can handle the try-catch in this utility function and wrap the original exception into a RuntimeException (or some other unchecked variant).
Instead, you have three primary approaches: Add a try/catch block to the lambda expression. Create an extracted method, as in the unchecked example. Write a wrapper method that catches checked exceptions and rethrows them as unchecked.
A lambda expression body can't throw any exceptions that haven't specified in a functional interface. If the lambda expression can throw an exception then the "throws" clause of a functional interface must declare the same exception or one of its subtype.
There's an IllegalArgumentException
in JDK which is unchecked and informs about wrong function input, so it can be used here:
IntStream.of(numbers)
.peek(n -> {
if (n < 0) throw new IllegalArgumentException(String.valueOf(n));
})
.sum();
In general, currently Java develops towards unchecked-only exceptions. There's even UncheckedIOException
class added in Java-8!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With