Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream throw exception in filter

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)
like image 230
paul Avatar asked Aug 22 '15 17:08

paul


People also ask

Can we throw exception in stream Java?

Unfortunately, we cannot do it in a Java stream because the map method accepts only a Function.

Can you handle exception in stream?

You can handle the try-catch in this utility function and wrap the original exception into a RuntimeException (or some other unchecked variant).

How do you handle exceptions in Java stream map?

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.

Can you throw any exception inside a lambda expression's body?

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.


Video Answer


1 Answers

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!

like image 60
Tagir Valeev Avatar answered Oct 01 '22 19:10

Tagir Valeev