D.Nursultan
D.Nursultan

Reputation: 51

How to throw an exception using lambda expression

I need to throw an exception if array contains a negative number.

What is best practices to do that using java8 features ?

Integer array = {11, -10, -20, -30, 10, 20, 30};

array.stream().filter(i -> i < 0) // then throw an exception

Upvotes: 0

Views: 231

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

You can use use Stream::anyMatch which return a boolean then if true thrown an exception like this:

boolean containsNegativeNumber = array.stream().anyMatch(i -> i < 0);
if (containsNegativeNumber) {
    throw new IllegalArgumentException("List contains negative numbers.");
}

Or directly as this:

if (array.stream().anyMatch(i -> i < 0)) {
    throw new IllegalArgumentException("List contains negative numbers.");
}

Upvotes: 3

Related Questions